package com.haoze.nurseapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.config.RedisUtil;
import com.haoze.common.dto.AgeDTO;
import com.haoze.common.dto.CronDescriber;
import com.haoze.common.dto.PushSocketMessage;
import com.haoze.common.dto.SocketMessageDTO;
import com.haoze.common.enumeration.StateEnum;
import com.haoze.common.model.OrdersFileIndexDataEntity;
import com.haoze.common.model.OrdersFileIndexEntity;
import com.haoze.common.model.TaskExecuteBatchEntity;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.*;
import com.haoze.nurseapp.dao.*;
import com.haoze.nurseapp.dto.*;
import com.haoze.nurseapp.dto.oral.OralMedicineListDTO;
import com.haoze.nurseapp.dto.task.OrdersFileIndexDataDTO;
import com.haoze.nurseapp.dto.task.TaskExecuteDetailDTO;
import com.haoze.nurseapp.enumeration.*;
import com.haoze.nurseapp.model.*;
import com.haoze.nurseapp.service.*;
import com.haoze.nurseapp.service.feign.PatientOrderService;
import com.haoze.nurseapp.vo.*;
import com.haoze.nurseapp.vo.specimen.SpecimenDetailVO;
import com.haoze.nurseapp.vo.specimen.SpecimenQrCodeStatusDto;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.common.utils.CopyOnWriteMap;
import org.quartz.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class TaskExecuteServiceImpl implements TaskExecuteService {

    private static final Logger log = LoggerFactory.getLogger(TaskExecuteServiceImpl.class);

    @Resource
    TaskExecuteMapper taskExecuteMapper;

    @Resource
    TaskExecuteDetailMapper taskExecuteDetailMapper;

    @Resource
    TaskExecuteBatchMapper taskExecuteBatchMapper;

    @Resource
    OrdersFileIndexDataMapper ordersFileIndexDataMapper;

    @Resource
    NursePatientOrderService nursePatientOrderService;

    @Resource
    PatientOrderService patientOrderServiceFeign;

    @Resource
    PatientMapper patientMapper;

    @Resource
    NurseFileIndexService fileIndexService;

    @Resource
    StaticCenterMapper staticCenterMapper;

    @Resource
    TransfusionMapper transfusionMapper;

    @Resource
    SpecimenService specimenService;

    @Autowired
    private PrintMarkMapper printMarkMapper;

    @Resource
    PuncureChannleMapper puncureChannleMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    TransactionDefinition transactionDefinition;

    @Autowired
    OralMedicineMapper oralMedicineMapper;

    @Resource
    OralOrdersRelationMapper oralOrdersRelationMapper;

    @Autowired
    SpecimenMapper specimenMapper;

    @Autowired
    OralMedicineService oralMedicineService;

    @Autowired
    private EmrFileMapper emrFileMapper;

    @Resource
    private PatientOrderService patientOrderService;

    @Autowired
    private AtomizeMedReturnMapper atomizeMedReturnMapper;
    @Autowired
    private AtomizeMedService atomizeMedService;

    @Autowired
    private UserMapper userMapper;

    private final String pfhl_NodeName = "皮肤护理";

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Result getDrugsByQrcode(String firstQrCode, String nodeId, String type, String secondQrCode) {

        Map<String, String> map = taskExecuteMapper.identifyOrderStatus(firstQrCode, secondQrCode);
        if (MapUtils.isEmpty(map)) {
            map = taskExecuteMapper.identifyOrderStatus(secondQrCode, firstQrCode);
        }
        if (MapUtils.isNotEmpty(map)) {
            if (map.get("cancelDatetime") != null) {
                return ResultGenerator.genFailedResult("该医嘱已取消");
            }

            if (map.get("planEndDatetime") != null && DateUtil.stringToDate(map.get("planEndDatetime")).getTime() < new Date().getTime()) {
                return ResultGenerator.genFailedResult("该医嘱已停止");
            }
        }

        if (QrScreenTypeEnum.WORK_SPACE_QRSCREEN.getEnumValue().equals(type)) {
            return nodeQrScreen(firstQrCode, nodeId);
        } else {
            return commonQrScreen(firstQrCode, secondQrCode);
        }
    }

    /**
     * 通用二维码扫描入口
     *
     * @param firstQrCode
     * @param secondQrCode
     * @return
     */
    public Result commonQrScreen(String firstQrCode, String secondQrCode) {

        Map<String, Object> resultMap = new HashMap<>(10);
        // 判断匹配
        if (StringUtils.isNotBlank(secondQrCode)) {

            String firstResult = taskExecuteMapper.identifyQrCodeMatch2(firstQrCode, secondQrCode, WorkSpaceEnum.INFUSION_CENTER.getNodeId());
            if (StringUtils.isNotBlank(firstResult)) {
                resultMap.put("returnQrCode", firstQrCode);
                resultMap.put("type", "1");
                resultMap.put("message", "腕带与药物匹配成功");
            } else {
                String secondResult = taskExecuteMapper.identifyQrCodeMatch2(secondQrCode, firstQrCode, WorkSpaceEnum.INFUSION_CENTER.getNodeId());
                if (StringUtils.isNotBlank(secondResult)) {
                    firstQrCode = secondQrCode;
                    resultMap.put("returnQrCode", firstQrCode);
                    resultMap.put("type", "1");
                    resultMap.put("message", "腕带与药物匹配成功");
                } else {
                    resultMap.put("returnQrCode", firstQrCode);
                    resultMap.put("type", "100");
                    resultMap.put("message", "腕带与药物不匹配");
                    return ResultGenerator.genOkResult(resultMap);
                }
            }

        } else {
            // 如果firstQrCode 是腕带或输液中心未执行，告诉前台
            Integer patientNum = patientMapper.queryPatientOrders(firstQrCode);
            if (patientNum > 0) {
                resultMap.put("returnQrCode", firstQrCode);
                resultMap.put("message", "请继续扫描药品编码");
                return ResultGenerator.genOkResult(resultMap);
            } else {
                String nowNodeId = taskExecuteDetailMapper.queryInfusionNodeId(firstQrCode, WorkSpaceEnum.INFUSION_CENTER.getNodeId());
                if (StringUtils.isNotBlank(nowNodeId)) {
                    resultMap.put("returnQrCode", firstQrCode);
                    resultMap.put("message", "请继续扫描病人腕带");
                    return ResultGenerator.genOkResult(resultMap);
                }
            }
        }

        // 查询qrCode关联的所有医嘱
        Map<String, String> map = taskExecuteMapper.queryQrInpatNumNoNode(firstQrCode);
        if (MapUtils.isEmpty(map)) {
            return ResultGenerator.genFailedResult("无当前类型任务需要执行");
        }

        // 根据用户病区获取指定病区的
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");

        // TODO: 目前只做了病区判断，后面需要根据具体节点具体权限范围设置进行判断
        String resultInpatNum = taskExecuteMapper.identifyAuthority(userId, map.get("inpatNum"));
        if (StringUtils.isBlank(resultInpatNum)) {
            return ResultGenerator.genFailedResult("您无权操作该任务");
        }

        Map<String, String> exeDetailNode = taskExecuteMapper.queryExecuteDetail(firstQrCode);
        if (MapUtils.isEmpty(exeDetailNode)) {
            return ResultGenerator.genFailedResult("未找到任务节点");
        }

        resultMap.put("qrCode", exeDetailNode.get("qrCode") == null ? "" : exeDetailNode.get("qrCode").toString());
        resultMap.put("barCode", exeDetailNode.get("barCode") == null ? "" : exeDetailNode.get("barCode").toString());
        resultMap.put("status", exeDetailNode.get("status").toString());
        resultMap.put("taskNodeId", exeDetailNode.get("taskNodeId").toString());
        resultMap.put("nodeId", exeDetailNode.get("nodeId").toString());
        //当扫描节点为静配收药时
        if (exeDetailNode.get("nodeId").equals(WorkSpaceEnum.STATIC_DRUG_COLLECTION.getNodeId())) {
            /*FileIndexDataEntity fileIndexDataEntity = taskExecuteMapper.queryFileIndexData(exeDetailNode.get("taskExecuteDetailId"));
            String status = null;
            String dataCode = null;
            //根据传入的barCode获取静配中心表数据
            StaticCenterEntity staticCenterEntity = staticCenterMapper.selectByPrimaryKey(exeDetailNode.get("barCode"));
            //根据barCode查询静配中心表是否已经加药
            if(staticCenterEntity!=null&&"1".equalsIgnoreCase(staticCenterEntity.getBatch())){
                status = "已加药";
                dataCode = "61224789ffe9413fb84c981f14ec13ad";
            }else if(staticCenterEntity!=null&&"0".equals(staticCenterEntity.getBatch())){
                status = "未加药";
                dataCode = "e08165457f3442beaf5a5674daabf6f3";//未加药："e08165457f3442beaf5a5674daabf6f3"     已加药：”61224789ffe9413fb84c981f14ec13ad
            }
            //若加药状态文书明细存在，则将查询到的是否加药添加到状态中
            if(fileIndexDataEntity!=null) {
                fileIndexDataEntity.setDataValue(status);
                fileIndexDataEntity.setDataCode(dataCode);
                nurseFileIndexDataMapper.updateByPrimaryKeySelective(fileIndexDataEntity);
            }*/
        } else if (exeDetailNode.get("nodeId").equals(WorkSpaceEnum.INFUSION_CENTER.getNodeId())) {
            // 当扫描节点为输液中心时
            resultMap.put("type", "1");
            resultMap.put("taskNodeName", "输液中心");
            resultMap.put("data", "");
            return ResultGenerator.genOkResult(resultMap);
        } else if (exeDetailNode.get("nodeId").equalsIgnoreCase(WorkSpaceEnum.INFUSION_COMPLETED.getNodeId())) {
            //根据当前任务节点获取输液中心节点文书
            String preEmrFileId = taskExecuteMapper.queryEmrFileId(firstQrCode);
            //根据文书ID获取模板数据树形结构
            EmrFile emrFile = fileIndexService.getFileIndex(preEmrFileId);
            resultMap.put("type", "2");
            resultMap.put("taskNodeName", "输液中");
            resultMap.put("data", emrFile);
            return ResultGenerator.genOkResult(resultMap);
        }

        WorkSpaceEnum.putTaskNodeSourceEnum();
        System.out.println(WorkSpaceEnum.ENUM_MAP);
        resultMap.put("taskNodeName", WorkSpaceEnum.ENUM_MAP.get(exeDetailNode.get("nodeId").toString()).getEnumName());
        resultMap.put("type", "0");

        String inpatNum = map.get("inpatNum");
        String inpatOrderId = map.get("inpatOrderId");
        if (StringUtils.isBlank(inpatNum)) {
            return ResultGenerator.genFailedResult("获取病人信息失败");
        }

        // 根据住院号和qrCode获取所有组内医嘱
        List<String> inpatOrderIds = taskExecuteMapper.queryInpatOrderIds(inpatNum, inpatOrderId);
        if (ArrayUtils.isEmpty(inpatOrderIds.toArray())) {
            inpatOrderIds = new ArrayList<>();
            inpatOrderIds.add(inpatOrderId);
        }
        //查询该Qrcode对应的医嘱信息中保存的病人信息，包括床号，入院号，姓名，用法（administration关联查询hsp_basic_data_value表中的data_value），医嘱开立时间
        //获取医嘱中病人信息
        Map<String, String> patientInfo = patientMapper.queryPatientInfo(inpatNum);

        // 根据医嘱获取医嘱所有子医嘱药品
        List<Map<String, String>> drugList = taskExecuteMapper.queryOrderDrugs(inpatOrderIds, inpatNum);

        if (ArrayUtils.isEmpty(drugList.toArray())) {
            return ResultGenerator.genFailedResult("这不是一个药品类医嘱");
        }

        //将查询结果拼接为前台需要的数据（床号，病案号，姓名，药品及剂量集合，用法，开立时间）
        OrderDrugsByQrcodeDTO orderDrugsByQrcodeDTO = new OrderDrugsByQrcodeDTO();
        orderDrugsByQrcodeDTO.setBedNo(patientInfo.get("bedNo"));
        orderDrugsByQrcodeDTO.setMedicalNum(patientInfo.get("medicalNum"));
        orderDrugsByQrcodeDTO.setPatName(patientInfo.get("patName"));
        orderDrugsByQrcodeDTO.setQrCode(firstQrCode);
        orderDrugsByQrcodeDTO.setDrugList(drugList);
        orderDrugsByQrcodeDTO.setAdministrtion(drugList.get(0).get("administration"));
        orderDrugsByQrcodeDTO.setNodeName(exeDetailNode.get("nodeId").toString());
        orderDrugsByQrcodeDTO.setPlanBeginTime(drugList.get(0).get("planBeginDatetime")); // 这个任务开始日期应该根据任务流第一个节点日期获取
        resultMap.put("data", orderDrugsByQrcodeDTO);
        resultMap.put("qrCode", firstQrCode);
        resultMap.put("barCode", firstQrCode);
        return ResultGenerator.genOkResult(resultMap);
    }

    /**
     * 节点进入扫描入口
     *
     * @return
     */
    private Result nodeQrScreen(String qrCode, String nodeId) {

        // 查询qrCode关联的所有医嘱
        Map<String, String> map = taskExecuteMapper.queryQrInpatNumByNode(qrCode, nodeId);
        if (MapUtils.isEmpty(map)) {
            return ResultGenerator.genFailedResult("无当前类型任务需要执行");
        }

        // 根据用户病区获取指定病区的
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");

        // TODO: 目前只做了病区判断，后面需要根据具体节点具体权限范围设置进行判断
        String resultInpatNum = taskExecuteMapper.identifyAuthority(userId, map.get("inpatNum"));
//        if (StringUtils.isBlank(resultInpatNum)) {
//            return ResultGenerator.genFailedResult("您无权操作该任务");
//        }

        String inpatNum = map.get("inpatNum");
        String inpatOrderId = map.get("inpatOrderId");
        if (StringUtils.isBlank(inpatNum)) {
            return ResultGenerator.genFailedResult("获取病人信息失败");
        }

        // 根据住院号和qrCode获取所有组内医嘱
        List<String> inpatOrderIds = taskExecuteMapper.queryInpatOrderIds(inpatNum, inpatOrderId);
        if (ArrayUtils.isEmpty(inpatOrderIds.toArray())) {
            inpatOrderIds = new ArrayList<>();
            inpatOrderIds.add(inpatOrderId);
        }
        //查询该Qrcode对应的医嘱信息中保存的病人信息，包括床号，入院号，姓名，用法（administration关联查询hsp_basic_data_value表中的data_value），医嘱开立时间
        //获取医嘱中病人信息
        Map<String, String> patientInfo = patientMapper.queryPatientInfo(inpatNum);

        // 根据医嘱获取医嘱所有子医嘱药品
        List<Map<String, String>> drugList = taskExecuteMapper.queryOrderDrugs(inpatOrderIds, inpatNum);

        //将查询结果拼接为前台需要的数据（床号，病案号，姓名，药品及剂量集合，用法，开立时间）
        OrderDrugsByQrcodeDTO orderDrugsByQrcodeDTO = new OrderDrugsByQrcodeDTO();
        orderDrugsByQrcodeDTO.setBedNo(patientInfo.get("bedNo"));
        orderDrugsByQrcodeDTO.setMedicalNum(patientInfo.get("medicalNum"));
        orderDrugsByQrcodeDTO.setPatName(patientInfo.get("patName"));
        orderDrugsByQrcodeDTO.setQrCode(qrCode);
        orderDrugsByQrcodeDTO.setDrugList(drugList);
        orderDrugsByQrcodeDTO.setAdministrtion(drugList.get(0).get("administration"));
        orderDrugsByQrcodeDTO.setPlanBeginTime(drugList.get(0).get("planBeginDatetime")); // 这个任务开始日期应该根据任务流第一个节点日期获取
        return ResultGenerator.genOkResult(orderDrugsByQrcodeDTO);
    }

    /**
     * 根据qrCode和nodeId获取当前节点taskNodeId
     */
    private String queryTaskNodeId(String qrCode, String nodeId) {
        String taskNodeId = taskExecuteMapper.queryTaskNodeIdByNodeId(qrCode, nodeId);
        return taskNodeId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result doProcess(Map<String, Object> map) {
        //获取当前任务节点
        String nodeId = (String) map.get("nodeId");
        if (WorkSpaceEnum.STATIC_DRUG_COLLECTION.getNodeId().equals(nodeId)) {
            return doNonStaticPrescription(map);
        } else {
            return doPushProcess(map);
        }
    }

    public Result doNonStaticPrescription(Map<String, Object> map) {
        String status = null;
        String dataCode = null;
        //获取qrCode列表
        List<String> brCodeList = (List<String>) map.get("qrCodes");
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        //循环前台传递的医嘱编号列表
        for (int i = 0; i < brCodeList.size(); i++) {
            //根据传入的barCode获取静配中心表数据
            StaticCenterEntity staticCenterEntity = staticCenterMapper.selectByPrimaryKey(brCodeList.get(i));
            if (staticCenterEntity != null && "1".equalsIgnoreCase(staticCenterEntity.getBatch())) {
                status = "已加药";
                dataCode = "61224789ffe9413fb84c981f14ec13ad";
            } else if (staticCenterEntity != null && "0".equals(staticCenterEntity.getBatch())) {
                status = "未加药";
                dataCode = "e08165457f3442beaf5a5674daabf6f3";//未加药："e08165457f3442beaf5a5674daabf6f3"     已加药：”61224789ffe9413fb84c981f14ec13ad
            }
            //遍历qrCode列表获取明细数据
            //TaskExecuteDetailEntity taskExecuteDetailEntity = taskExecuteMapper.queryTaskExecute(brCodeList.get(i), WorkSpaceEnum.STATIC_DRUG_COLLECTION.getNodeId());
            TaskExecuteDetailDTO taskExecuteDetailDTO = taskExecuteMapper.queryTaskExecuteInfo(brCodeList.get(i), WorkSpaceEnum.STATIC_DRUG_COLLECTION.getNodeId());
            OrdersFileIndexDataEntity fileIndexDataEntity = taskExecuteMapper.queryFileIndexData(taskExecuteDetailDTO.getTaskExecuteDetailId());
            if (fileIndexDataEntity != null) {
                fileIndexDataEntity.setDataValue(status);
                fileIndexDataEntity.setDataCode(dataCode);
                ordersFileIndexDataMapper.updateByPrimaryKeySelective(fileIndexDataEntity);
                //根据当前节点数据启动下一节点（调用doctor模块方法createNextTaskNode）
                nursePatientOrderService.createNextTaskNode(taskExecuteDetailDTO.getTaskExecuteDetailId(), taskExecuteDetailDTO.getBatchNo(), userId, taskExecuteDetailDTO.getGroupId() == null ? "" : taskExecuteDetailDTO.getGroupId(), "", null, "", null);
            }
        }
        return ResultGenerator.genOkResult();
    }

    public Result doPushProcess(Map<String, Object> map) {
        List<String> qrCodes = (List<String>) map.get("qrCodes");

        Set<String> qrCodesSet = new HashSet<>();
        for (String qrCode : qrCodes) {
            qrCodesSet.add(qrCode);
        }

        if (qrCodesSet.size() != qrCodes.size()) {
            return ResultGenerator.genFailedResult("二维码重复");
        }

        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //userId = "bf533ba10ec64ab0bbf360c44fa7a787";

        // 查询当前节点是否正处在待完成
        List<TaskExecuteBatchEntity> taskExecuteDetailEntitys = taskExecuteDetailMapper.queryExecuteDetail(qrCodes);
        List<Map<String, Object>> list = new CopyOnWriteArrayList<>();
        for (int j = 0; j < taskExecuteDetailEntitys.size(); j++) {
            Map<String, Object> entityMap = new HashMap<>();
            TaskExecuteBatchEntity taskExecuteDetailEntity = taskExecuteDetailEntitys.get(j);
            taskExecuteDetailEntity.setExecutePersonId(userId);
            entityMap.put("taskExecuteDetailEntity", taskExecuteDetailEntity);
            entityMap.put("userId", userId);
            list.add(entityMap);
        }
        nursePatientOrderService.createNextTaskNodeList(list, "");

        return ResultGenerator.genOkResult("成功");
    }

    @Override
    public Result getWorkbenchInfo() {
        WorkSpaceEnum.putSourceEnum();
        // 移除第一个出入量总结，总结是在列表进行
        Map<String, WorkSpaceEnum> map = WorkSpaceEnum.ENUM_MAP;
        Map<String, WorkSpaceEnum> tempMap = new HashMap();
        for (String key : map.keySet()) {
            WorkSpaceEnum typeEnum = (WorkSpaceEnum) map.get(key);
            tempMap.put(typeEnum.getNodeKey(), typeEnum);
        }
        return ResultGenerator.genOkResult(tempMap);
    }

    @Override
    public List<Map<String, String>> queryTaskNum(String nodeId, String currentDate, String wardId) {
        //获取传递的日期并修改为数据库比对的格式。,
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        //获取登录人ID
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        String queryDate = null;
        try {
            queryDate = sdf.format(sdf.parse(currentDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Map<String, String> taskNumList = taskExecuteMapper.queryTaskNum(nodeId, queryDate, userId, wardId);
        List list = new ArrayList();
        list.add(taskNumList);
        return list;
    }

    @Override
    public PageInfo<Map<String, Object>> getTasks(Map<String, Object> map) {
        String taskName = (String) map.get("taskName");
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>();
        if ("all".equals(taskName)) {
            pageInfo = getAllTasks(map);
        } else if ("unfinished".equals(taskName)) {
            pageInfo = getFailedTasks(map);
        } else if ("finished".equals(taskName)) {
            pageInfo = getPerformedTasks(map);
        } else if ("reject".equals(taskName)) {
            pageInfo = getReturnTasks(map);
        }
        return pageInfo;
    }

    public PageInfo<Map<String, Object>> getAllTasks(Map<String, Object> map) {
        String currentDate = (String) map.get("currentDate");
        String nodeId = (String) map.get("nodeId");
        String search = (String) map.get("search");
        String wardId = (String) map.get("wardId");
        int page = (int) map.get("page");
        int pageSize = (int) map.get("pageSize");
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
//        userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        //获取传递的日期并修改为数据库比对的格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        String queryDate = null;
        try {
            queryDate = sdf.format(sdf.parse(currentDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<Map<String, String>> allTaskInfo1 = taskExecuteMapper.queryAllTaskInfo(nodeId, queryDate, search, userId, wardId);
        List<String> qrCodeList = new ArrayList<>();
        for (int i = 0; i < allTaskInfo1.size(); i++) {
            if (!qrCodeList.contains(allTaskInfo1.get(i).get("qrCode"))) {
                qrCodeList.add(allTaskInfo1.get(i).get("qrCode"));
            }
        }
        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> allTaskInfo = taskExecuteMapper.queryAllTaskInfo(nodeId, queryDate, search, userId, wardId);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < allTaskInfo.size(); i++) {
            if (!list.contains(allTaskInfo.get(i).get("qrCode"))) {
                list.add(allTaskInfo.get(i).get("qrCode"));
            }
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (String str : list) {
            List<Map<String, String>> lm = new ArrayList<>();
            Map<String, Object> resultMap = new HashMap<>();
            String bedNo = null;
            String medicalNum = null;
            String patName = null;
            String beginTime = null;
            String administrtion = null;
            String qrCode = null;
            String status = null;
            String executeTime = null;
            String executePerson = null;
            String reTime = null;
            String reReason = null;
            String reNurse = null;
            String modifyTime = null;
            String remark = null;
            String bedLabel = null;
            for (int i = 0; i < allTaskInfo.size(); i++) {
                System.out.println(allTaskInfo.get(i).get("qrCode"));
                if (str.equals(allTaskInfo.get(i).get("qrCode"))) {
                    bedNo = allTaskInfo.get(i).get("bedNo");
                    bedLabel = allTaskInfo.get(i).get("bedLabel");
                    medicalNum = allTaskInfo.get(i).get("medicalNum");
                    patName = allTaskInfo.get(i).get("patName");
                    beginTime = allTaskInfo.get(i).get("beginTime");
                    modifyTime = allTaskInfo.get(i).get("modifyTime");
                    administrtion = allTaskInfo.get(i).get("administrtion");
                    executeTime = allTaskInfo.get(i).get("executeTime");
                    executePerson = allTaskInfo.get(i).get("executePerson");
                    qrCode = allTaskInfo.get(i).get("qrCode");
                    status = allTaskInfo.get(i).get("status");
                    remark = allTaskInfo.get(i).get("remark");
                    Map<String, String> hm = new HashMap<>();
                    hm.put("inpatOrderDataId", allTaskInfo.get(i).get("inpatOrderDataId"));
                    hm.put("drugs", allTaskInfo.get(i).get("drugs"));
                    hm.put("number", allTaskInfo.get(i).get("number"));
                    hm.put("unit", allTaskInfo.get(i).get("unit"));
                    lm.add(hm);
                }
            }
            resultMap.put("bedNo", bedNo);
            resultMap.put("bedLabel", bedLabel);
            resultMap.put("medicalNum", medicalNum);
            resultMap.put("patName", patName);
            resultMap.put("beginTime", beginTime);
            resultMap.put("modifyTime", modifyTime);
            resultMap.put("administrtion", administrtion);
            resultMap.put("qrCode", qrCode);
            resultMap.put("status", status);
            resultMap.put("drugsList", lm);
            resultMap.put("executeTime", executeTime);
            resultMap.put("executePerson", executePerson);
            resultMap.put("reTime", reTime);
            resultMap.put("reReason", reReason);
            resultMap.put("reNurse", reNurse);
            resultMap.put("remark", remark);
            if(StringUtils.isNotBlank(qrCode)){
                if(qrCode.startsWith("y_")){
                    String code = qrCode.split("_")[1];
                    String freqTime = DateUtil.dateToString(DateUtil.stringToDate(code.substring(code.length()-14),"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm");
                    resultMap.put("freqTime", freqTime);
                }else if(qrCode.startsWith("kr_")){
                    String tCode = taskExecuteMapper.queryOralOrdersRelationByQrCode(qrCode, null);
                    if(StringUtils.isNotBlank(tCode)){
                        String code = qrCode.split("_")[1];
                        String freqTime = DateUtil.dateToString(DateUtil.stringToDate("20"+code.substring(code.length()-14),"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm");
                        resultMap.put("freqTime", freqTime);
                    }
                }else if(qrCode.startsWith("j_")){
                    String code = qrCode.split("_")[1];
                    code = "20"+code.substring(medicalNum.length());
                    String freqTime = DateUtil.dateToString(DateUtil.stringToDate(code.substring(0,14),"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm");
                    resultMap.put("freqTime", freqTime);
                }
            }
            resultList.add(resultMap);
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
        pageInfo.setTotal(qrCodeList.size());
        return pageInfo;
    }

    public PageInfo<Map<String, Object>> getPerformedTasks(Map<String, Object> map) {
        String currentDate = (String) map.get("currentDate");
        String nodeId = (String) map.get("nodeId");
        String search = (String) map.get("search");
        int page = (int) map.get("page");
        String wardId = (String) map.get("wardId");
        int pageSize = (int) map.get("pageSize");
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //获取传递的日期并修改为数据库比对的格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        String queryDate = null;
        try {
            queryDate = sdf.format(sdf.parse(currentDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
//        List<Map<String, String>> performedTaskInfo1 = taskExecuteMapper.queryPerformedTaskInfo(nodeId, queryDate, search, userId, wardId);
//        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> performedTaskInfo = taskExecuteMapper.queryPerformedTaskInfo(nodeId, queryDate, search, userId, wardId);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < performedTaskInfo.size(); i++) {
            if (!list.contains(performedTaskInfo.get(i).get("qrCode"))) {
                list.add(performedTaskInfo.get(i).get("qrCode"));
            }
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (String str : list) {
            List<Map<String, String>> lm = new ArrayList<>();
            Map<String, Object> resultMap = new HashMap<>();
            String bedNo = null;
            String medicalNum = null;
            String patName = null;
            String beginTime = null;
            String administrtion = null;
            String qrCode = null;
            String status = null;
            String executeTime = null;
            String executePerson = null;
            String reTime = null;
            String reReason = null;
            String reNurse = null;
            String remark = null;
            String bedLabel=null;
            for (int i = 0; i < performedTaskInfo.size(); i++) {
                if (str.equals(performedTaskInfo.get(i).get("qrCode"))) {
                    bedNo = performedTaskInfo.get(i).get("bedNo");
                    medicalNum = performedTaskInfo.get(i).get("medicalNum");
                    patName = performedTaskInfo.get(i).get("patName");
                    beginTime = performedTaskInfo.get(i).get("beginTime");
                    administrtion = performedTaskInfo.get(i).get("administrtion");
                    qrCode = performedTaskInfo.get(i).get("qrCode");
                    status = performedTaskInfo.get(i).get("status");
                    executeTime = performedTaskInfo.get(i).get("executeTime");
                    executePerson = performedTaskInfo.get(i).get("executePerson");
                    remark = performedTaskInfo.get(i).get("remark");
                    bedLabel = performedTaskInfo.get(i).get("bedLabel");
                    Map<String, String> hm = new HashMap<>();
                    hm.put("inpatOrderDataId", performedTaskInfo.get(i).get("inpatOrderDataId"));
                    hm.put("drugs", performedTaskInfo.get(i).get("drugs"));
                    hm.put("number", performedTaskInfo.get(i).get("number"));
                    hm.put("unit", performedTaskInfo.get(i).get("unit"));
                    lm.add(hm);
                }
            }
            resultMap.put("bedNo", bedNo);
            resultMap.put("bedLabel", bedLabel);
            resultMap.put("medicalNum", medicalNum);
            resultMap.put("patName", patName);
            resultMap.put("beginTime", beginTime);
            resultMap.put("administrtion", administrtion);
            resultMap.put("qrCode", qrCode);
            resultMap.put("status", status);
            resultMap.put("executeTime", executeTime);
            resultMap.put("executePerson", executePerson);
            resultMap.put("reTime", reTime);
            resultMap.put("reReason", reReason);
            resultMap.put("reNurse", reNurse);
            resultMap.put("remark", remark);
            resultMap.put("drugsList", lm);
            if(StringUtils.isNotBlank(qrCode)){
                if(qrCode.startsWith("y_")){
                    String code = qrCode.split("_")[1];
                    String freqTime = DateUtil.dateToString(DateUtil.stringToDate(code.substring(code.length()-14),"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm");
                    resultMap.put("freqTime", freqTime);
                }else if(qrCode.startsWith("kr_")){
                    String tCode = taskExecuteMapper.queryOralOrdersRelationByQrCode(qrCode, null);
                    if(StringUtils.isNotBlank(tCode)){
                        String code = qrCode.split("_")[1];

                        String freqTime = DateUtil.dateToString(DateUtil.stringToDate("20"+code.substring(code.length()-14),"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm");
                        resultMap.put("freqTime", freqTime);
                    }
                }else if(qrCode.startsWith("j_")){
                    String code = qrCode.split("_")[1];
                    code = "20"+code.substring(medicalNum.length());
                    String freqTime = DateUtil.dateToString(DateUtil.stringToDate(code.substring(0,14),"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm");
                    resultMap.put("freqTime", freqTime);
                }
            }
            resultList.add(resultMap);
        }
        int total = resultList.size();
        if (page != 0 && pageSize != 0) {
            resultList = resultList.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
        pageInfo.setTotal(total);
//        pageInfo.setTotal(performedTaskInfo1.size());
        return pageInfo;
    }


    public PageInfo<Map<String, Object>> getFailedTasks(Map<String, Object> map) {
        String currentDate = (String) map.get("currentDate");
        String nodeId = (String) map.get("nodeId");
        String search = (String) map.get("search");
        String wardId = (String) map.get("wardId");
        int page = (int) map.get("page");
        int pageSize = (int) map.get("pageSize");
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //获取传递的日期并修改为数据库比对的格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        String queryDate = null;
        try {
            queryDate = sdf.format(sdf.parse(currentDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
//        List<Map<String, String>> failedTaskInfo1 = taskExecuteMapper.queryFailedTaskInfo(nodeId, queryDate, search, userId, wardId); 组医嘱分页有问题
//        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> failedTaskInfo = taskExecuteMapper.queryFailedTaskInfo(nodeId, queryDate, search, userId, wardId);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < failedTaskInfo.size(); i++) {
            if (!list.contains(failedTaskInfo.get(i).get("qrCode"))) {
                list.add(failedTaskInfo.get(i).get("qrCode"));
            }
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (String str : list) {
            List<Map<String, String>> lm = new ArrayList<>();
            Map<String, Object> resultMap = new HashMap<>();
            String bedNo = null;
            String medicalNum = null;
            String patName = null;
            String beginTime = null;
            String administrtion = null;
            String qrCode = null;
            String status = null;
            String executeTime = null;
            String executePerson = null;
            String reTime = null;
            String reReason = null;
            String reNurse = null;
            String remark = null;
            String bedLabel=null;
            for (int i = 0; i < failedTaskInfo.size(); i++) {
                if (str.equals(failedTaskInfo.get(i).get("qrCode"))) {
                    bedNo = failedTaskInfo.get(i).get("bedNo");
                    medicalNum = failedTaskInfo.get(i).get("medicalNum");
                    patName = failedTaskInfo.get(i).get("patName");
                    beginTime = failedTaskInfo.get(i).get("beginTime");
                    administrtion = failedTaskInfo.get(i).get("administrtion");
                    qrCode = failedTaskInfo.get(i).get("qrCode");
                    status = failedTaskInfo.get(i).get("status");
                    remark = failedTaskInfo.get(i).get("remark");
                    bedLabel = failedTaskInfo.get(i).get("bedLabel");
                    Map<String, String> hm = new HashMap<>();
                    hm.put("inpatOrderDataId", failedTaskInfo.get(i).get("inpatOrderDataId"));
                    hm.put("drugs", failedTaskInfo.get(i).get("drugs"));
                    hm.put("number", failedTaskInfo.get(i).get("number"));
                    hm.put("unit", failedTaskInfo.get(i).get("unit"));
                    lm.add(hm);
                }
            }
            resultMap.put("bedNo", bedNo);
            resultMap.put("bedLabel", bedLabel);
            resultMap.put("medicalNum", medicalNum);
            resultMap.put("patName", patName);
            resultMap.put("beginTime", beginTime);
            resultMap.put("administrtion", administrtion);
            resultMap.put("qrCode", qrCode);
            resultMap.put("status", status);
            resultMap.put("drugsList", lm);
            resultMap.put("executeTime", executeTime);
            resultMap.put("executePerson", executePerson);
            resultMap.put("reTime", reTime);
            resultMap.put("reReason", reReason);
            resultMap.put("reNurse", reNurse);
            resultMap.put("remark", remark);
            if(StringUtils.isNotBlank(qrCode)){
                if(qrCode.startsWith("y_")){
                    String code = qrCode.split("_")[1];
                    String freqTime = DateUtil.dateToString(DateUtil.stringToDate(code.substring(code.length()-14),"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm");
                    resultMap.put("freqTime", freqTime);
                }else if(qrCode.startsWith("j_")){
                    String code = qrCode.split("_")[1];
                    code = "20"+code.substring(medicalNum.length());
                    String freqTime = DateUtil.dateToString(DateUtil.stringToDate(code.substring(0,14),"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm");
                    resultMap.put("freqTime", freqTime);
                }else if(qrCode.startsWith("kr_")){
                    String tCode = taskExecuteMapper.queryOralOrdersRelationByQrCode(qrCode, null);
                    if(StringUtils.isNotBlank(tCode)){
                        String code = qrCode.split("_")[1];
                        System.out.println(code);
                        System.out.println(code.substring(code.length()-12));
                        String freqTime = DateUtil.dateToString(DateUtil.stringToDate("20"+code.substring(code.length()-14),"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm");
                        resultMap.put("freqTime", freqTime);
                    }
                }
            }
            resultList.add(resultMap);
        }
        int total = resultList.size();
        if (page != 0 && pageSize != 0) {
            resultList = resultList.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
        pageInfo.setTotal(total);
//        pageInfo.setTotal(failedTaskInfo1.size());
        return pageInfo;
    }

    public PageInfo<Map<String, Object>> getReturnTasks(Map<String, Object> map) {
        String currentDate = (String) map.get("currentDate");
        String nodeId = (String) map.get("nodeId");
        String search = (String) map.get("search");
        String wardId = (String) map.get("wardId");
        int page = (int) map.get("page");
        int pageSize = (int) map.get("pageSize");
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //获取传递的日期并修改为数据库比对的格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        String queryDate = null;
        try {
            queryDate = sdf.format(sdf.parse(currentDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<Map<String, String>> returnTasks1 = taskExecuteMapper.queryReturnTasks(nodeId, queryDate, search, userId, wardId);
        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> returnTasks = taskExecuteMapper.queryReturnTasks(nodeId, queryDate, search, userId, wardId);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < returnTasks.size(); i++) {
            if (!list.contains(returnTasks.get(i).get("qrCode"))) {
                list.add(returnTasks.get(i).get("qrCode"));
            }
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (String str : list) {
            List<Map<String, String>> lm = new ArrayList<>();
            Map<String, Object> resultMap = new HashMap<>();
            String bedNo = null;
            String medicalNum = null;
            String patName = null;
            String beginTime = null;
            String administrtion = null;
            String qrCode = null;
            String executeTime = null;
            String executePerson = null;
            String reTime = null;
            String reReason = null;
            String reNurse = null;
            String remark = null;
            String bedLabel = null;
            for (int i = 0; i < returnTasks.size(); i++) {
                if (str.equals(returnTasks.get(i).get("qrCode"))) {
                    bedNo = returnTasks.get(i).get("bedNo");
                    medicalNum = returnTasks.get(i).get("medicalNum");
                    patName = returnTasks.get(i).get("patName");
                    beginTime = returnTasks.get(i).get("beginTime");
                    administrtion = returnTasks.get(i).get("administrtion");
                    reTime = returnTasks.get(i).get("reTime");
                    reReason = returnTasks.get(i).get("reReason");
                    reNurse = returnTasks.get(i).get("reNurse");
                    qrCode = returnTasks.get(i).get("qrCode");
                    remark = returnTasks.get(i).get("remark");
                    bedLabel = returnTasks.get(i).get("bedLabel");
                    Map<String, String> hm = new HashMap<>();
                    hm.put("inpatOrderDataId", returnTasks.get(i).get("inpatOrderDataId"));
                    hm.put("drugs", returnTasks.get(i).get("drugs"));
                    hm.put("number", returnTasks.get(i).get("number"));
                    hm.put("unit", returnTasks.get(i).get("unit"));
                    lm.add(hm);
                }
            }
            resultMap.put("bedNo", bedNo);
            resultMap.put("bedLabel", bedLabel);
            resultMap.put("qrCode", qrCode);
            resultMap.put("medicalNum", medicalNum);
            resultMap.put("patName", patName);
            resultMap.put("beginTime", beginTime);
            resultMap.put("administrtion", administrtion);
            resultMap.put("drugsList", lm);
            resultMap.put("executeTime", executeTime);
            resultMap.put("executePerson", executePerson);
            resultMap.put("reTime", reTime);
            resultMap.put("reReason", reReason);
            resultMap.put("reNurse", reNurse);
            resultMap.put("remark", remark);
            if(StringUtils.isNotBlank(qrCode)){
                if(qrCode.startsWith("y_")){
                    String code = qrCode.split("_")[1];
                    String freqTime = DateUtil.dateToString(DateUtil.stringToDate(code.substring(code.length()-14),"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm");
                    resultMap.put("freqTime", freqTime);
                }else if(qrCode.startsWith("kr_")){
                    String tCode = taskExecuteMapper.queryOralOrdersRelationByQrCode(qrCode, null);
                    if(StringUtils.isNotBlank(tCode)){
                        String code = qrCode.split("_")[1];
                        String freqTime = DateUtil.dateToString(DateUtil.stringToDate("20"+code.substring(code.length()-14),"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm");
                        resultMap.put("freqTime", freqTime);
                    }
                }else if(qrCode.startsWith("j_")){
                    String code = qrCode.split("_")[1];
                    code = "20"+code.substring(medicalNum.length());
                    String freqTime = DateUtil.dateToString(DateUtil.stringToDate(code.substring(0,14),"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm");
                    resultMap.put("freqTime", freqTime);
                }
            }
            resultList.add(resultMap);
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
        pageInfo.setTotal(returnTasks1.size());
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result createBatchQrcode(Map<String, Object> map) {
        List brCodeList = new ArrayList();

        // 打印批次数量（默认批次数量递增）
        Integer batchNum = (Integer) map.get("batchNum");
        String inpatOrderId = (String) map.get("inpatOrderId");
        String taskId = (String) map.get("taskId"); // 指定任务类型
        String taskNodeId = (String) map.get("taskNodeId"); // 指定节点（页面选择，有扫码属性的节点可以创建）
        // 根据医嘱获取医嘱二维码编号，在医嘱二维码编号后加批次编号
        String orderQrCode = taskExecuteMapper.queryOrderQrcode(inpatOrderId);

        List<String> noQrcodeList = taskExecuteMapper.queryNoBatchQrcode(inpatOrderId, taskNodeId, taskId);
        String qrcodeNum = taskExecuteMapper.queryOwnBatchQrcodeSum(inpatOrderId, taskNodeId, taskId);
        String qrCode = "";
        // 只有第一次创建qrCode才会无法获取qrCodeNum
        if (StringUtils.isBlank(qrcodeNum)) {
            qrCode = orderQrCode + "0000";
        } else {
            qrCode = qrcodeNum;
        }

        if (noQrcodeList.size() <= batchNum) {
            for (String executeBatchId : noQrcodeList) {
                String lastForeStr = qrCode.substring(qrCode.length() - 4);
                String lastForeStrTemp = String.format("%04d", Integer.valueOf(lastForeStr) + 1);
                qrCode = qrCode.substring(0, qrCode.length() - 4) + lastForeStrTemp;
                taskExecuteMapper.updateQrcodeByDetailId(qrCode, executeBatchId, "");
                brCodeList.add(qrCode);
            }

            // 获取最后一条执行详情实体
            Integer needInsertSize = batchNum - noQrcodeList.size();
            String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
            userId = "bf533ba10ec64ab0bbf360c44fa7a787";
            List<String> qrCodes = new ArrayList<>();
            List<String> barCodes = new ArrayList<>();
            for (int j = 0; j < needInsertSize; j++) {
                String lastForeStr = qrCode.substring(qrCode.length() - 4);
                String lastForeStrTemp = String.format("%04d", Integer.valueOf(lastForeStr) + 1);
                qrCode = qrCode.substring(0, qrCode.length() - 4) + lastForeStrTemp;
                // 拷贝1号批次文书记录创建
                brCodeList.add(qrCode);
                qrCodes.add(qrCode);
                barCodes.add("");
            }
            TaskCopyNodeDTO taskCopyNodeDTO = new TaskCopyNodeDTO();
            taskCopyNodeDTO.setBarCodes(barCodes);
            taskCopyNodeDTO.setQrCodes(qrCodes);
            taskCopyNodeDTO.setInpatOrderId(inpatOrderId);
            taskCopyNodeDTO.setUserId(userId);
            taskCopyNodeDTO.setTaskNodeId(taskNodeId);
            taskCopyNodeDTO.setTaskId(taskId);
            patientOrderServiceFeign.copyLastNode(taskCopyNodeDTO);
        } else {
            for (int i = 0; i < batchNum; i++) {
                String lastForeStr = qrCode.substring(qrCode.length() - 4);
                String lastForeStrTemp = String.format("%04d", Integer.valueOf(lastForeStr) + 1);
                qrCode = qrCode.substring(0, qrCode.length() - 4) + lastForeStrTemp;
                String executeDetailId = noQrcodeList.get(i);
                taskExecuteMapper.updateQrcodeByDetailId(qrCode, executeDetailId, "");
                brCodeList.add(qrCode);
            }

        }

        return ResultGenerator.genOkResult(brCodeList);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result createPivasBatchQrcode(Map<String, Object> map) {
        List brCodeList = new ArrayList();

        // 打印批次数量（默认批次数量递增）
        Integer batchNum = (Integer) map.get("batchNum");
        String inpatOrderId = (String) map.get("inpatOrderId");
        String type = (String) map.get("type");
        String barcode = (String) map.get("barcode");
        String taskId = (String) map.get("taskId");
        String taskNodeId = (String) map.get("taskNodeId");
        String dosingStatus = (String) map.get("dosingStatus");

        // 根据医嘱获取医嘱二维码编号，在医嘱二维码编号后加批次编号
        String orderQrCode = taskExecuteMapper.queryOrderQrcode(inpatOrderId);

        // 查询所有待执行摆药核对节点个数
        List<String> noQrcodeList = taskExecuteMapper.queryNoBatchQrcode(inpatOrderId, taskNodeId, taskId);
        String qrcodeNum = taskExecuteMapper.queryOwnBatchQrcodeSum(inpatOrderId, taskNodeId, taskId);
        String qrCode = "";
        // 只有第一次创建qrCode才会无法获取qrCodeNum
        if (StringUtils.isBlank(qrcodeNum)) {
            qrCode = orderQrCode + "0000";
        } else {
            qrCode = qrcodeNum;
        }

        if (noQrcodeList.size() <= batchNum) {
            for (String executeDetailId : noQrcodeList) {
                String lastForeStr = qrCode.substring(qrCode.length() - 4);
                String lastForeStrTemp = String.format("%04d", Integer.valueOf(lastForeStr) + 1);
                qrCode = qrCode.substring(0, qrCode.length() - 4) + lastForeStrTemp;
                taskExecuteMapper.updateQrcodeByDetailId(qrCode, executeDetailId, barcode);
                brCodeList.add(qrCode);
            }

            // 获取最后一条执行详情实体
            Integer needInsertSize = batchNum - noQrcodeList.size();
            //String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
            String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
            List<String> qrCodes = new ArrayList<>();
            List<String> barCodes = new ArrayList<>();
            for (int j = 0; j < needInsertSize; j++) {
                String lastForeStr = qrCode.substring(qrCode.length() - 4);
                String lastForeStrTemp = String.format("%04d", Integer.valueOf(lastForeStr) + 1);
                qrCode = qrCode.substring(0, qrCode.length() - 4) + lastForeStrTemp;
                // 拷贝1号批次文书记录创建
                brCodeList.add(qrCode);
                qrCodes.add(qrCode);
                barCodes.add(barcode);
            }
            TaskCopyNodeDTO taskCopyNodeDTO = new TaskCopyNodeDTO();
            taskCopyNodeDTO.setBarCodes(barCodes);
            taskCopyNodeDTO.setQrCodes(qrCodes);
            taskCopyNodeDTO.setInpatOrderId(inpatOrderId);
            taskCopyNodeDTO.setUserId(userId);
            taskCopyNodeDTO.setTaskNodeId(taskNodeId);
            taskCopyNodeDTO.setTaskId(taskId);
            patientOrderServiceFeign.copyLastNode(taskCopyNodeDTO);
        } else {
            for (int i = 0; i < batchNum; i++) {
                String lastForeStr = qrCode.substring(qrCode.length() - 4);
                String lastForeStrTemp = String.format("%04d", Integer.valueOf(lastForeStr) + 1);
                qrCode = qrCode.substring(0, qrCode.length() - 4) + lastForeStrTemp;
                String executeDetailId = noQrcodeList.get(i);
                taskExecuteMapper.updateQrcodeByDetailId(qrCode, executeDetailId, barcode);
                brCodeList.add(qrCode);
            }

        }
        //未加药："e08165457f3442beaf5a5674daabf6f3"     已加药：”61224789ffe9413fb84c981f14ec13ad
        String status = "";
        String dataCode = "";
        if ("1".equalsIgnoreCase(dosingStatus)) {
            status = "已加药";
            dataCode = "61224789ffe9413fb84c981f14ec13ad";
        } else {
            status = "未加药";
            dataCode = "e08165457f3442beaf5a5674daabf6f3";
        }
        //根据医嘱ID和节点ID获取静配中心文书内容，并添加加药状态
        for (int i = 0; i < noQrcodeList.size(); i++) {
            OrdersFileIndexDataEntity fileIndexDataEntity = taskExecuteMapper.queryFileIndexData(noQrcodeList.get(i));
            if (fileIndexDataEntity != null) {
                fileIndexDataEntity.setDataValue(status);
                fileIndexDataEntity.setDataCode(dataCode);
                ordersFileIndexDataMapper.updateByPrimaryKeySelective(fileIndexDataEntity);
            }
        }
        return ResultGenerator.genOkResult();
    }

    @Override
    public List<OrdersFileIndexDataEntity> getOrderInfoByBarCode(String barCode) {
        List<OrdersFileIndexDataEntity> fileIndexDataEntityList = taskExecuteMapper.queryInfoByBarCode(barCode);
        return fileIndexDataEntityList;
    }

    @Override
    public Result getOrdersInfo(String qrCode) {
        Map<String, String> map = taskExecuteMapper.queryInpatNumAndOrderNo(qrCode);
        if (MapUtils.isEmpty(map)) {
            return ResultGenerator.genFailedResult("未找到当前任务");
        }
        String inpatNum = map.get("inpatNum").toString();
        String inpatOrderId = map.get("inpatOrderId").toString();
        // 根据住院号和qrCode获取所有组内医嘱
        List<String> inpatOrderIds = taskExecuteMapper.queryInpatOrderIds(inpatNum, inpatOrderId);
        if (ArrayUtils.isEmpty(inpatOrderIds.toArray())) {
            inpatOrderIds = new ArrayList<>();
            inpatOrderIds.add(inpatOrderId);
        }
        //查询该Qrcode对应的医嘱信息中保存的病人信息，包括床号，入院号，姓名，用法（administration关联查询hsp_basic_data_value表中的data_value），医嘱开立时间
        //获取医嘱中病人信息
        Map<String, String> patientInfo = patientMapper.queryPatientInfo(inpatNum);

        // 根据医嘱获取医嘱所有子医嘱药品
        List<Map<String, String>> drugList = taskExecuteMapper.queryOrderDrugs(inpatOrderIds, inpatNum);

        if (ArrayUtils.isEmpty(drugList.toArray())) {
            return ResultGenerator.genFailedResult("这不是一个药品类医嘱");
        }

        //将查询结果拼接为前台需要的数据（床号，病案号，姓名，药品及剂量集合，用法，开立时间）
        OrderDrugsByQrcodeDTO orderDrugsByQrcodeDTO = new OrderDrugsByQrcodeDTO();
        orderDrugsByQrcodeDTO.setBedNo(patientInfo.get("bedNo"));
        orderDrugsByQrcodeDTO.setMedicalNum(patientInfo.get("medicalNum"));
        orderDrugsByQrcodeDTO.setPatName(patientInfo.get("patName"));
        orderDrugsByQrcodeDTO.setQrCode(qrCode);
        orderDrugsByQrcodeDTO.setDrugList(drugList);
        orderDrugsByQrcodeDTO.setAdministrtion(drugList.get(0).get("administration"));
        orderDrugsByQrcodeDTO.setPlanBeginTime(drugList.get(0).get("planBeginDatetime")); // 这个任务开始日期应该根据任务流第一个节点日期获取
        orderDrugsByQrcodeDTO.setOrdersRemark(drugList.get(0).get("ordersRemark"));
        orderDrugsByQrcodeDTO.setFreq(drugList.get(0).get("freq"));
        return ResultGenerator.genOkResult(orderDrugsByQrcodeDTO);
    }

    //checkQrCode也要调用此方法，只返回正确结果，所以这个方法的错误信息需要throw Exception

    /**
     *
     * @param qrCode
     * @param ctlId
     * @param showFlag
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result screenQrCode(String qrCode, String ctlId, String showFlag) {
        String isStop = atomizeMedReturnMapper.queryIsStop(qrCode);
        if (StringUtils.isNotEmpty(isStop)) {
            throw new RuntimeException("任务已终止！");
        }
        TaskNodeVO taskNodeVO = new TaskNodeVO();
        taskNodeVO.setNodeType(NodeEnterEnum.NORMAL.getValue());
        taskNodeVO.setNodeTypeName(NodeEnterEnum.NORMAL.getText());
        taskNodeVO.setQrCode(qrCode);
        taskNodeVO.setSpecialNodeType(SpecialNodeEnum.NORMAL.getValue());
        taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.NORMAL.getText());
        try {
            //暂时先用这种方法处理执行时间，后续如果其他类型也需要这样显示 需要另外想方法
            String[] qrCodes = qrCode.split("_");
            String executeTimeStr = qrCodes[1].substring(qrCodes[1].length() - 14);
            Date executeTime = DateUtil.stringToDate(executeTimeStr, "yyyyMMddHHmmss");
            String execTimeStr = DateUtil.dateToString(executeTime, "yyyy-MM-dd HH:mm:ss");
            taskNodeVO.setExecTime(execTimeStr);
        } catch (Exception e) {
            taskNodeVO.setExecTime(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        }
        taskNodeVO.setOrderInfoList(new ArrayList<>());
        if (qrCode.indexOf("k_") > -1 && "1".equals(showFlag)) {
            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.ORALMEDICINE.getValue());
            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.ORALMEDICINE.getText());
            return ResultGenerator.genOkResult(taskNodeVO);
        }
        List packageData = oralMedicineService.getPackingMachine(qrCode);
        if (packageData != null && packageData.size() > 0) {
            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.ORALMEDICINE.getValue());
            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.ORALMEDICINE.getText());
            return ResultGenerator.genOkResult(taskNodeVO);
        }
        // 腕带
        String inpatNum = taskExecuteMapper.queryInpatNumByQrcode(qrCode);
        if (StringUtils.isNotBlank(inpatNum)) {
            taskNodeVO.setNodeType(NodeEnterEnum.WRISTBAND.getValue());
            taskNodeVO.setNodeTypeName(NodeEnterEnum.WRISTBAND.getText());
            taskNodeVO.setOrderInfoList(new ArrayList<>());
            return ResultGenerator.genOkResult(taskNodeVO);
        } else {
            // 床头牌
            String bedcard = taskExecuteMapper.queryBedcardByQrcode(qrCode);
            if (StringUtils.isNotBlank(bedcard)) {
                taskNodeVO.setNodeType(NodeEnterEnum.BEDCARD.getValue());
                taskNodeVO.setNodeTypeName(NodeEnterEnum.BEDCARD.getText());
                taskNodeVO.setOrderInfoList(new ArrayList<>());
                return ResultGenerator.genOkResult(taskNodeVO);
            }
        }
        // 标本采集
        try {
            SpecimenDetailVO specimenDetailVO = specimenService.querySpecimen(qrCode, showFlag);
            if (specimenDetailVO != null) {
                specimenDetailVO.setQrCode(qrCode);
                if (specimenDetailVO.getNodeInfoVOs().stream().allMatch(x -> SpecimenFlowEnum.SPECIMEN_READY.getNodeId().equals(x.getNodeId()))) {
                    String testTubeColor = specimenMapper.selectSysTestTubeColorBySpecimenNum(specimenDetailVO.getSpecimenNum());
                    if (StringUtils.isNotBlank(testTubeColor)) {
                        specimenDetailVO.setCellColor(testTubeColor);
                    }
                    //if(null!=specimenDetailVO.getCellColor() && !specimenDetailVO.getCellColor().contains("#")){
                        /*String color = Long.toHexString(Long.valueOf(specimenDetailVO.getCellColor()));
                        final int colorSize = 6;
                        int size = color.length();
                        if(size < colorSize){
                            for (int i = 0; i < colorSize - size; i++){
                                color += "0";
                            }
                        }*/
                    //}
                    specimenDetailVO.setSpecialNodeType(SpecialNodeEnum.SPECIMEN.getValue());
                    specimenDetailVO.setSpecialNodeTypeName(SpecialNodeEnum.SPECIMEN.getText());
                    return ResultGenerator.genOkResult(specimenDetailVO);
                }
                // 标本采集
                else if (specimenDetailVO.getNodeInfoVOs().stream().allMatch(x -> SpecimenFlowEnum.SPECIMEN_COLLECT.getNodeId().equals(x.getNodeId()))) {
                    return ResultGenerator.genFailedResult(NodeEnterEnum.WRISTBAND.getText() + "执行任务，请先扫描腕带");
                    //多人核对
                } else if (specimenDetailVO.getNodeInfoVOs().stream().allMatch(x -> SpecimenFlowEnum.SPECIMEN_DOUBLE_CHECK.getNodeId().equals(x.getNodeId()))) {
                    return ResultGenerator.genFailedResult(NodeEnterEnum.WRISTBAND.getText() + "执行任务，请先扫描腕带");
                    //标本转运
                } else if (specimenDetailVO.getNodeInfoVOs().stream().allMatch(x -> SpecimenFlowEnum.SPECIMEN_TRANSFER.getNodeId().equals(x.getNodeId()))) {
                    specimenDetailVO.setSpecialNodeType(SpecialNodeEnum.SPECIMEN_TRANSFER.getValue());
                    specimenDetailVO.setSpecialNodeTypeName(SpecialNodeEnum.SPECIMEN_TRANSFER.getText());
                    //specimenDetailVO.setSpecimenNum(qrCode);
                    return ResultGenerator.genOkResult(specimenDetailVO);
                } else {
                    throw new RuntimeException(qrCode + "未找到任务节点");
                }
            }

        } catch (Exception ex) {
            log.error("标本采集出错", ex);
            return ResultGenerator.genFailedResult(ex.getMessage());
        }

        Long start = new Date().getTime();
        boolean genBoolean = false;
        //根据预生成的qrcode，生成实际的任务批次
        Result genResult = generatTaskByQrcode(qrCode);
        if(genResult.getCode() == 400){
            return genResult;
        }else{
            genBoolean=true;
        }
        //if (!generatTaskByQrcode(qrCode) && StringUtils.isEmpty(inpatNum)) {
        if (!genBoolean && StringUtils.isEmpty(inpatNum)) {
            throw new RuntimeException("任务执行中，请重试");
        }
        Long second = new Date().getTime();
        log.info("生成任务耗时：：：：：：：：：：：：：：：：：：：：：：：：：：：{}", second - start);

        NodeInfoDTO nodeInfoDTO = taskExecuteMapper.queryWaitExecuteNode(qrCode);
        if (nodeInfoDTO == null) {
            log.error("qrcode:" + qrCode + "没有任务节点");
            throw new RuntimeException("无当前类型任务需要执行");
        }
        taskNodeVO.setNodeName(nodeInfoDTO.getNodeName());

        Map<String, String> map = taskExecuteMapper.identifyOrderStatus(qrCode, "");
        if (MapUtils.isNotEmpty(map) && !pfhl_NodeName.equals(nodeInfoDTO.getNodeName())) {
            String statusStr = checkOrderStatus(map.get("inpatOrderId"), null);
            if (StringUtils.isNotEmpty(statusStr)) {
                throw new RuntimeException(statusStr);
            }
        }

        if (pfhl_NodeName.equals(nodeInfoDTO.getNodeName())) {
            if (!OrderStatusEnum.ORDER_STOP_HIS.getValue().equals(map.get("execStatusHis"))) {
                throw new RuntimeException("医嘱未停止，无法执行任务！");
            } else {
                //执行时间取医嘱停止时间，bug编号7534
                taskNodeVO.setExecTime(map.get("planEndDatetime"));
            }
        }

        if (null != nodeInfoDTO.getNodeEnter() && nodeInfoDTO.getNodeEnter().equals(NodeEnterEnum.WRISTBAND.getValue())) {
            return ResultGenerator.genFailedResult(NodeEnterEnum.WRISTBAND.getText() + "执行任务，请先扫描腕带");
        } else if (null != nodeInfoDTO.getNodeEnter() && nodeInfoDTO.getNodeEnter().equals(NodeEnterEnum.BEDCARD.getValue())) {
            return ResultGenerator.genFailedResult(NodeEnterEnum.BEDCARD.getText() + "执行任务，请先扫描床头牌");
        }


        if (nodeInfoDTO.getNodeId().equals(SpecialNodeEnum.NEWINFLUSION.getNodeId())) {
            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.NEWINFLUSION.getValue());
            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.NEWINFLUSION.getText());
        }

        if (nodeInfoDTO.getNodeId().equals(SpecialNodeEnum.DEPTCHECKBLOOD.getNodeId())) {
            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.DEPTCHECKBLOOD.getValue());
            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.DEPTCHECKBLOOD.getText());
        }

        if (nodeInfoDTO.getNodeId().equals(SpecialNodeEnum.STATICCENTER.getNodeId())) {
            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.STATICCENTER.getValue());
            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.STATICCENTER.getText());
        }

        String taskName = taskExecuteMapper.getTaskNameByQrCode(qrCode);
        if (ConstsEnum.TASK_NAME_JMZS.getName().equals(taskName)) {
            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.JMZS.getValue());
            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.JMZS.getText());
        } else if (ConstsEnum.TASK_NAME_WHLC.getName().equals(taskName)) {
            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.WHLC.getValue());
            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.WHLC.getText());
        } else if (ConstsEnum.TASK_NAME_CNYY.getName().equals(taskName)) {
            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.CNYY.getValue());
            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.CNYY.getText());
        }

        if (showFlag.equals("0")) {
            taskNodeVO.setOrderInfoList(new ArrayList<>());
            return ResultGenerator.genOkResult(taskNodeVO);
        }

        // 查询qrCode关联的所有医嘱
        Map<String, String> ordersMap = taskExecuteMapper.queryQrInpatNumNoNode(qrCode);
        if (MapUtils.isEmpty(ordersMap)) {
            throw new RuntimeException("无当前类型任务需要执行");
        }

        // 根据用户病区获取指定病区的
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");

        // TODO: 目前只做了病区判断，后面需要根据具体节点具体权限范围设置进行判断
//        String resultInpatNum = taskExecuteMapper.identifyAuthority(userId, map.get("inpatNum"));
//        if (StringUtils.isBlank(resultInpatNum)) {
//            return ResultGenerator.genFailedResult("您无权操作该任务");
//        }

        Map<String, String> patientMap = patientMapper.queryPatientInfo(nodeInfoDTO.getInpatNum());
        PatientInfo patientInfo = new PatientInfo();
        patientInfo.setWardName(patientMap.get("wardName"));
        patientInfo.setDeptName(patientMap.get("deptName"));
        patientInfo.setMedicalNum(nodeInfoDTO.getMedicalNum());
        patientInfo.setBedNo(nodeInfoDTO.getBedNo());
        patientInfo.setBedLabel(patientMap.get("bedLabel"));
        patientInfo.setSex(nodeInfoDTO.getSex());
        //计算年龄
        patientInfo.setAge(computeAge(nodeInfoDTO));
        patientInfo.setPatName(nodeInfoDTO.getPatName());
        taskNodeVO.setPatientInfo(patientInfo);
        long third = new Date().getTime();
        log.info("生成任务后，生成文书前耗时：：：：：：：：：：：：：：：：：：：：：：：：：：：：：{}", third - second);
        List<OrderInfo> orderInfoList = taskExecuteMapper.queryOrderInfos(nodeInfoDTO.getInpatOrderId(), nodeInfoDTO.getInpatNum());
        String orderInfoFreq = taskExecuteMapper.queryOrderInfoFreq(nodeInfoDTO.getInpatOrderId());
        orderInfoList.get(0).setFreq((org.apache.commons.lang3.StringUtils.isBlank(orderInfoList.get(0).getFreq()) ? "" : orderInfoList.get(0).getFreq()) + " " + (org.apache.commons.lang3.StringUtils.isBlank(orderInfoFreq) ? "" : orderInfoFreq));

        taskNodeVO.setOrderInfoList(orderInfoList);
        if (StringUtils.isNotBlank(nodeInfoDTO.getEmrFileId())) {
            EmrFile emrFile = fileIndexService.getFileIndex(nodeInfoDTO.getEmrFileId());
            if (null != emrFile && null != emrFile.getEmrFileIndexEntity() && null != emrFile.getEmrFileIndexEntity().getTplId()) {
                taskNodeVO.setChildCataLog(taskExecuteMapper.queryChildCataLogByTplId(emrFile.getEmrFileIndexEntity().getTplId()));
                if (CollectionUtils.isNotEmpty(taskNodeVO.getChildCataLog())) {
                    taskNodeVO.getChildCataLog().add(taskExecuteMapper.queryParentCataLogByTplId(emrFile.getEmrFileIndexEntity().getTplId()));
                }
            }
            if (StringUtils.isEmpty(ctlId)) {
                taskNodeVO.setEmrFile(emrFile);
            } else {
                TaskExecuteBatchEntity taskExecuteBatchEntity = taskExecuteBatchMapper.selectByPrimaryKey(nodeInfoDTO.getTaskBatchId());
                taskNodeVO.setEmrFile(saveEmrFile(taskExecuteBatchEntity, ctlId, emrFile));
            }
        }
        long four = new Date().getTime();
        log.info("获取文书耗时：：：：：：：：：：：：：：：：：：：：：：：：：：：：：{}", four - third);
        taskNodeVO.setNodeName(nodeInfoDTO.getNodeName());
        taskNodeVO.setTaskNodeId(nodeInfoDTO.getTaskNodeId());

        return ResultGenerator.genOkResult(taskNodeVO);

    }


    /**
     * 计算年龄
     *
     * @param nodeInfoDTO
     * @return 年龄
     */
    private String computeAge(NodeInfoDTO nodeInfoDTO) {
        AgeDTO ageDTO = new AgeDTO();
        ageDTO.setAgeYear(nodeInfoDTO.getAgeYear());
        ageDTO.setAgeMonth(nodeInfoDTO.getAgeMonth());
        ageDTO.setAgeDay(nodeInfoDTO.getAgeDay());
        ageDTO.setAgeHour(nodeInfoDTO.getAgeHour());
        ageDTO.setAgeMinute(nodeInfoDTO.getAgeMinute());
        ageDTO.setInDateTime(nodeInfoDTO.getInDatetime());
        ageDTO.setBirthday(nodeInfoDTO.getBirthDay());
        return DateUtil.getAge(ageDTO);
    }

    public EmrFile saveEmrFile(TaskExecuteBatchEntity taskExecuteBatchEntity, String ctlId, EmrFile emrFile) {
        Map<String, Object> paramMap = new HashMap<>();
        String createTplId = taskExecuteMapper.queryTplIdByCtlId(ctlId);
        if (createTplId.equals(emrFile.getEmrFileIndexEntity().getTplId())) {
            return emrFile;
        }
        TaskExecuteEntity taskExecuteEntity = taskExecuteMapper.selectByPrimaryKey(taskExecuteBatchEntity.getTaskExecuteId());
        paramMap.put("tplId", createTplId);
        paramMap.put("taskExecuteEntity", taskExecuteEntity);
        paramMap.put("userId", taskExecuteMapper.getUserIdByTaskExecuteId(taskExecuteEntity.getInpatorderdataId()));
        paramMap.put("taskNodeId", taskExecuteBatchEntity.getTaskNodeId());
        paramMap.put("taskExeDetailId", taskExecuteBatchEntity.getTaskExecuteDetailId());
        paramMap.put("taskBatchId", taskExecuteBatchEntity.getTaskBatchId());
        EmrFileIndexEntity emrFileIndexEntity = patientOrderServiceFeign.createTaskNodeOrderFileIndex(paramMap);
        log.info("创建文书：文书id：" + emrFileIndexEntity.getEmrFileId() + "。任务批次id：" + taskExecuteBatchEntity.getTaskBatchId());
        return fileIndexService.getFileIndex(emrFileIndexEntity.getEmrFileId());
    }

    @Override
    public Result screenQrCodeInCenter(String qrCode) {

        TaskNodeVO taskNodeVO = new TaskNodeVO();
        taskNodeVO.setNodeType(NodeEnterEnum.NORMAL.getValue());
        taskNodeVO.setNodeTypeName(NodeEnterEnum.NORMAL.getText());
        taskNodeVO.setQrCode(qrCode);

        // 腕带
        String inpatNum = taskExecuteMapper.queryInpatNumByQrcode(qrCode);
        if (StringUtils.isNotBlank(inpatNum)) {
            return ResultGenerator.genFailedResult("重复扫码腕带");
        } else {
            // 床头牌
            String bedcard = taskExecuteMapper.queryBedcardByQrcode(qrCode);
            if (StringUtils.isNotBlank(bedcard)) {
                return ResultGenerator.genFailedResult("重复扫码床头牌");
            }
        }

        Map<String, String> map = taskExecuteMapper.identifyOrderStatus(qrCode, "");
        if (MapUtils.isNotEmpty(map)) {
            if (map.get("cancelDatetime") != null) {
                return ResultGenerator.genFailedResult("该医嘱已取消");
            }

            if (map.get("planEndDatetime") != null && map.get("planEndDatetime").compareTo(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")) < 0) {
                return ResultGenerator.genFailedResult("该医嘱已停止");
            }

//			if (map.get("confirmDatetime") == null || (!map.get("confirmDatetime").equals(map.get("createDatetime")) && !map.get("confirmDatetime").equals(DateUtil.dateToString(DateUtil.getDateBefore(new Date(), 1), "yyyy-MM-dd")))) {
//				return ResultGenerator.genFailedResult("医嘱尚未确认，无法执行");
//			}
        }

        NodeInfoDTO nodeInfoDTO = taskExecuteMapper.queryWaitExecuteNode(qrCode);
        if (nodeInfoDTO == null) {
            return ResultGenerator.genFailedResult("未找到任务节点");
        }

//        if (nodeInfoDTO.getNodeEnter().equals(NodeEnterEnum.WRISTBAND.getValue())) {
//            return ResultGenerator.genFailedResult(NodeEnterEnum.WRISTBAND.getText() + "执行任务，请先扫描腕带");
//        } else if (nodeInfoDTO.getNodeEnter().equals(NodeEnterEnum.BEDCARD.getValue())) {
//            return ResultGenerator.genFailedResult(NodeEnterEnum.BEDCARD.getText() + "执行任务，请先扫描床头牌");
//        }
//
//        taskNodeVO.setSpecialNodeType(SpecialNodeEnum.NORMAL.getValue());
//        taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.NORMAL.getText());
//        if (nodeInfoDTO.getNodeId().equals(SpecialNodeEnum.NEWINFLUSION.getNodeId())) {
//            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.NEWINFLUSION.getValue());
//            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.NEWINFLUSION.getText());
//        }

        // 查询qrCode关联的所有医嘱
        Map<String, String> ordersMap = taskExecuteMapper.queryQrInpatNumNoNode(qrCode);
        if (MapUtils.isEmpty(ordersMap)) {
            return ResultGenerator.genFailedResult("无当前类型任务需要执行");
        }

        // 根据用户病区获取指定病区的
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");

        // TODO: 目前只做了病区判断，后面需要根据具体节点具体权限范围设置进行判断
//        String resultInpatNum = taskExecuteMapper.identifyAuthority(userId, map.get("inpatNum"));
//        if (StringUtils.isBlank(resultInpatNum)) {
//            return ResultGenerator.genFailedResult("您无权操作该任务");
//        }

        PatientInfo patientInfo = new PatientInfo();
        patientInfo.setMedicalNum(nodeInfoDTO.getMedicalNum());
        patientInfo.setBedNo(nodeInfoDTO.getBedNo());
        patientInfo.setSex(nodeInfoDTO.getSex());
        patientInfo.setAge(nodeInfoDTO.getAgeYear());
        patientInfo.setPatName(nodeInfoDTO.getPatName());
        taskNodeVO.setPatientInfo(patientInfo);

        List<OrderInfo> orderInfoList = taskExecuteMapper.queryOrderInfos(nodeInfoDTO.getInpatOrderId(), nodeInfoDTO.getInpatNum());
        taskNodeVO.setOrderInfoList(orderInfoList);
        if (StringUtils.isNotBlank(nodeInfoDTO.getEmrFileId())) {
            EmrFile emrFile = fileIndexService.getFileIndex(nodeInfoDTO.getEmrFileId());
            taskNodeVO.setEmrFile(emrFile);
        }

        taskNodeVO.setNodeName(nodeInfoDTO.getNodeName());
        return ResultGenerator.genOkResult(taskNodeVO);

    }

    @Override
    @Transactional
    public Result passNode(TaskNodeDTO taskNode) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        String emrFileId = "";
        //根据taskNodeId，qrCode获取当前任务节点是否执行，未执行则继续执行，若有另外的设备执行过当前节点则返回
        Integer taskTemp = taskExecuteBatchMapper.queryInfoByTaskNodeId(taskNode.getQrCode(), taskNode.getTaskNodeId());
        if (taskTemp != 1) {
            return ResultGenerator.genFailedResult("当前任务已执行完毕，请重新扫码执行下一任务！");
        }
        TaskExecuteDetailDTO executeDetailDTO = taskExecuteDetailMapper.queryTaskExecuteDetailInfo(taskNode.getQrCode());
        if (null != executeDetailDTO && null != executeDetailDTO.getInpatorderdataId()) {
            String statusStr = checkOrderStatus(executeDetailDTO.getInpatorderdataId(), null);
            NodeInfoDTO nodeInfoDTO = taskExecuteMapper.queryWaitExecuteNode(taskNode.getQrCode());
            if (!(pfhl_NodeName.equals(nodeInfoDTO.getNodeName()))) {
                if (StringUtils.isNotEmpty(statusStr)) {
                    return ResultGenerator.genFailedResult(statusStr);
                }
            }
        }
        if (taskNode.getEmrFile().getEmrFileIndexEntity() != null) {
            emrFileId = fileIndexService.saveFileIndex(taskNode.getEmrFile());
        }
        List<OrdersFileIndexDataDTO> fileData = ordersFileIndexDataMapper.selectDataByEmrFileId(emrFileId);
        List<EmrFileData> fileDataList = flatConvert2(taskNode.getEmrFile().getEmrFileDataList());
        AtomicReference<Boolean> canBZ = new AtomicReference<>(false);
        AtomicReference<Boolean> whlcResult = new AtomicReference<>(false);
        String taskName = taskExecuteMapper.getTaskNameByQrCode(taskNode.getQrCode());
        if (TaskEnum.TASK_NAME_WHLC.getText().equals(taskName)) {
            //雾化流程
            this.whlcFeature(fileDataList, executeDetailDTO, taskNode.getQrCode(), userId, whlcResult);
        } else {
            //输液、注射流程
            this.sylcFeature(fileDataList, executeDetailDTO, fileData, canBZ, userId);
        }
        String qrCode = taskNode.getQrCode();
        if (!canBZ.get()) {
            if (taskNode.getQrCode().length() == 14 && isNumeric(taskNode.getQrCode())) {
                qrCode = taskExecuteBatchMapper.selectBatchCountByQrcode(taskNode.getQrCode()).getQrCode();
            }
            String stopFlag = null;
            if (TaskEnum.TASK_NAME_WHLC.getText().equals(taskName) && whlcResult.get()) {
                stopFlag = TaskEnum.TASKSTOP.getValue();
            }
            nursePatientOrderService.createNextTaskNode(executeDetailDTO.getTaskExecuteDetailId(), executeDetailDTO.getBatchNo(), userId, executeDetailDTO.getGroupId() == null ? "" : executeDetailDTO.getGroupId(), "", null, qrCode, stopFlag);
        }
        return ResultGenerator.genOkResult();
    }

    private void whlcFeature(List<EmrFileData> fileDataList, TaskExecuteDetailDTO executeDetailDTO, String qrCode, String userId, AtomicReference<Boolean> whlcResult) {
        //雾化确认节点进行回收处理
        if (VarCodeEnum.WHQR.getVarCode().equalsIgnoreCase(executeDetailDTO.getVarCode())) {
            String returnReason = fileDataList.stream().filter(file -> VarCodeEnum.WHYWHSYY.getVarCode().equals(file.getElement().getVarCode())).map(file -> file.getFileIndexDataEntity().getDataValue()).collect(Collectors.joining());
            if (StringUtils.isNotEmpty(returnReason)) {
                if (VarCodeEnum.QT.getName().equals(returnReason)) {
                    returnReason = fileDataList.stream().filter(file -> VarCodeEnum.QT.getVarCode().equals(file.getElement().getVarCode())).map(file -> file.getFileIndexDataEntity().getDataValue()).collect(Collectors.joining());
                }
                Map<String, String> patientInfo = patientMapper.queryPatientInfo(executeDetailDTO.getInpatNum());
                AtomizeMedReturnEntity atomizeMedReturnEntity = new AtomizeMedReturnEntity();
                atomizeMedReturnEntity.setReturnId(UUIDUtil.randomString());
                atomizeMedReturnEntity.initAdd();
                atomizeMedReturnEntity.setInpatNum(executeDetailDTO.getInpatNum());
                atomizeMedReturnEntity.setQrCode(qrCode);
                atomizeMedReturnEntity.setInpatorderdataId(executeDetailDTO.getInpatorderdataId());
                atomizeMedReturnEntity.setDeptId(patientInfo.get("deptId"));
                atomizeMedReturnEntity.setWardDeptId(patientInfo.get("wardDeptId"));
                atomizeMedReturnEntity.setReturnReason(returnReason);
                atomizeMedReturnEntity.setReturnTime(new Timestamp(System.currentTimeMillis()));
                atomizeMedReturnEntity.setReturnUserId(userId);
                atomizeMedReturnEntity.setDelFlag(ConstsEnum.DEFAULT_NO.getIndex());
                atomizeMedReturnEntity.setType(ConstsEnum.ATOMIZE_MED_RETURN_ONE.getIndex());
                atomizeMedReturnMapper.insert(atomizeMedReturnEntity);
            }
        } else if (VarCodeEnum.WHGY.getVarCode().equalsIgnoreCase(executeDetailDTO.getVarCode())) {
            atomizeMedReturnMapper.updateByQrCode(qrCode);
        }
        //雾化终止
        AtomicBoolean whzz = new AtomicBoolean(false);
        fileDataList.stream().filter(file -> VarCodeEnum.WHCL.getVarCode().equals(file.getElement().getVarCode())).forEach(file -> {
            if (VarCodeEnum.WHCL.getName().equals(file.getFileIndexDataEntity().getDataValue())) {
                whzz.set(true);
            }
        });
        if (whzz.get()) {
            String returnReason = fileDataList.stream().filter(file -> VarCodeEnum.WHYWHSYY.getVarCode().equals(file.getElement().getVarCode())).map(file -> file.getFileIndexDataEntity().getDataValue()).collect(Collectors.joining());
            if (VarCodeEnum.QT.getName().equals(returnReason)) {
                returnReason = fileDataList.stream().filter(file -> VarCodeEnum.QT.getVarCode().equals(file.getElement().getVarCode())).map(file -> file.getFileIndexDataEntity().getDataValue()).collect(Collectors.joining());
            }
            Map<String, String> patientInfo = patientMapper.queryPatientInfo(executeDetailDTO.getInpatNum());
            AtomizeMedReturnEntity atomizeMedReturnEntity = new AtomizeMedReturnEntity();
            atomizeMedReturnEntity.setReturnId(UUIDUtil.randomString());
            atomizeMedReturnEntity.initAdd();
            atomizeMedReturnEntity.setInpatNum(executeDetailDTO.getInpatNum());
            atomizeMedReturnEntity.setQrCode(qrCode);
            atomizeMedReturnEntity.setInpatorderdataId(executeDetailDTO.getInpatorderdataId());
            atomizeMedReturnEntity.setDeptId(patientInfo.get("deptId"));
            atomizeMedReturnEntity.setWardDeptId(patientInfo.get("wardDeptId"));
            atomizeMedReturnEntity.setReturnReason(returnReason);
            atomizeMedReturnEntity.setReturnTime(new Timestamp(System.currentTimeMillis()));
            atomizeMedReturnEntity.setReturnUserId(userId);
            atomizeMedReturnEntity.setDelFlag(ConstsEnum.DEFAULT_NO.getIndex());
            atomizeMedReturnEntity.setType(ConstsEnum.ATOMIZE_MED_RETURN_TWO.getIndex());
            atomizeMedReturnMapper.insert(atomizeMedReturnEntity);
        }
        whlcResult.set(whzz.get());
    }

    private void sylcFeature(List<EmrFileData> fileDataList, TaskExecuteDetailDTO executeDetailDTO, List<OrdersFileIndexDataDTO> fileData, AtomicReference<Boolean> canBZ, String userId) {
        AtomicBoolean fhsyzx = new AtomicBoolean(false);
        fileDataList.parallelStream().filter(file -> VarCodeEnum.FHSYZX.getVarCode().equals(file.getElement().getVarCode())).forEach(file -> {
            if (VarCodeEnum.FHSYZX.getName().equals(file.getFileIndexDataEntity().getDataValue())) {
                fhsyzx.set(true);
            }
        });

        //新增穿刺，新增通道，换瓶需要保存数据到PUNCTURE_CHANNLE
        if (null != executeDetailDTO.getVarCode()
                && (executeDetailDTO.getVarCode().equalsIgnoreCase(VarCodeEnum.RWJD_XZCC.getVarCode())
                || executeDetailDTO.getVarCode().equalsIgnoreCase(VarCodeEnum.RWJD_XZTD.getVarCode())
                || executeDetailDTO.getVarCode().equalsIgnoreCase(VarCodeEnum.RWJD_HP.getVarCode())
                || executeDetailDTO.getVarCode().equalsIgnoreCase(VarCodeEnum.RWJD_SYXS.getVarCode())) && !fhsyzx.get()) {
            PuncureChannleEntity puncureChannleEntity = new PuncureChannleEntity();
            puncureChannleEntity.initAdd();
            puncureChannleEntity.setPunctureChannleId(UUIDUtil.randomString());
            puncureChannleEntity.setBatchNo(String.valueOf(executeDetailDTO.getBatchNo()));
            puncureChannleEntity.setInpatNum(executeDetailDTO.getInpatNum());
            puncureChannleEntity.setInpatorderdataId(executeDetailDTO.getInpatorderdataId());
            fileData.forEach(x -> {
                if (VarCodeEnum.SYZX_INSTRUMENT.getVarCode().equalsIgnoreCase(x.getVarCode())) {
                    puncureChannleEntity.setInstrumentElementId(x.getElementId());
                    puncureChannleEntity.setInstrumentValue(x.getDataValue());
                }
                if (VarCodeEnum.SYZX_PASSSTATE.getVarCode().equalsIgnoreCase(x.getVarCode())) {
                    puncureChannleEntity.setChannleTypeElementId(x.getElementId());
                    puncureChannleEntity.setChannleTypeValue(x.getDataValue());
                }
                if (VarCodeEnum.SYZX_NODE.getVarCode().equalsIgnoreCase(x.getVarCode())) {
                    puncureChannleEntity.setPointElementId(x.getElementId());
                    puncureChannleEntity.setPointValue(x.getDataValue());
                }
                if (VarCodeEnum.SYZX_TOOL.getVarCode().equalsIgnoreCase(x.getVarCode())) {
                    puncureChannleEntity.setToolElementId(x.getElementId());
                    puncureChannleEntity.setToolValue(x.getDataValue());
                    fileData.parallelStream().filter(y -> null != y.getParentFileIndexDataId() && y.getParentFileIndexDataId().equalsIgnoreCase(x.getFileIndexDataId())).forEach(z -> {
                        puncureChannleEntity.setToolPositionElementId(z.getElementId());
                        puncureChannleEntity.setToolPositionValue(z.getDataValue());
                    });
                }
                if (VarCodeEnum.SYZX_SPEED.getVarCode().equalsIgnoreCase(x.getVarCode())) {
                    puncureChannleEntity.setSpeedElementId(x.getElementId());
                    puncureChannleEntity.setSpeedValue(x.getDataValue());
                }
            });
            if (executeDetailDTO.getVarCode().equalsIgnoreCase(VarCodeEnum.RWJD_HP.getVarCode()) || executeDetailDTO.getVarCode().equalsIgnoreCase(VarCodeEnum.RWJD_SYXS.getVarCode())) {
                List<PuncureChannleEntity> puncureChannleEntityList = puncureChannleMapper.selectOneByOrderAndBatch(executeDetailDTO.getInpatorderdataId(), executeDetailDTO.getBatchNo());
                if (CollectionUtils.isNotEmpty(puncureChannleEntityList)) {
                    PuncureChannleEntity puncureChannle = puncureChannleEntityList.get(0);
                    puncureChannle.setSpeedElementId(StringUtils.isNotEmpty(puncureChannleEntity.getSpeedElementId()) ? puncureChannleEntity.getSpeedElementId() : puncureChannle.getSpeedElementId());
                    puncureChannle.setSpeedValue(StringUtils.isNotEmpty(puncureChannleEntity.getSpeedValue()) ? puncureChannleEntity.getSpeedValue() : puncureChannle.getSpeedValue());
                    puncureChannle.setChannleTypeElementId(StringUtils.isNotEmpty(puncureChannleEntity.getChannleTypeElementId()) ? puncureChannleEntity.getChannleTypeElementId() : puncureChannle.getChannleTypeElementId());
                    puncureChannle.setChannleTypeValue(StringUtils.isNotEmpty(puncureChannleEntity.getChannleTypeValue()) ? puncureChannleEntity.getChannleTypeValue() : puncureChannle.getChannleTypeValue());
                    puncureChannle.setInstrumentElementId(StringUtils.isNotEmpty(puncureChannleEntity.getInstrumentElementId()) ? puncureChannleEntity.getInstrumentElementId() : puncureChannle.getInstrumentElementId());
                    puncureChannle.setInstrumentValue(StringUtils.isNotEmpty(puncureChannleEntity.getInstrumentValue()) ? puncureChannleEntity.getInstrumentValue() : puncureChannle.getInstrumentValue());
                    puncureChannle.setModifyTime(new Date());
                    puncureChannleMapper.updateByPrimaryKeySelective(puncureChannle);
                }
            } else {
                puncureChannleMapper.insert(puncureChannleEntity);
            }
        }
        //结束输液需要把穿刺和通道信息去掉
        if (VarCodeEnum.RWJD_SYXS.getVarCode().equalsIgnoreCase(executeDetailDTO.getVarCode())) {
            fileData.stream().forEach(x -> {
                //封管删除通道信息
                if (VarCodeEnum.JSFS_FG.getVarCode().equalsIgnoreCase(x.getDataCode())) {
                    //判断当前要删除的穿刺和通道是否为最后一个，如果是最后一个则只删除通道信息，保留穿刺点，穿刺工具，穿刺部位
                    List<PuncureChannleEntity> list = this.puncureChannleMapper.selectPointListByOrderId(executeDetailDTO.getInpatorderdataId(), executeDetailDTO.getBatchNo());
                    if (CollectionUtils.isNotEmpty(list)) {
                        if (list.size() == 1) {
                            PuncureChannleEntity puncureChannleEntity = list.get(0);
                            puncureChannleEntity.setSpeedValue("");
                            puncureChannleEntity.setSpeedElementId("");
                            puncureChannleEntity.setChannleTypeValue("");
                            puncureChannleEntity.setChannleTypeElementId("");
                            puncureChannleEntity.setInstrumentValue("");
                            puncureChannleEntity.setInstrumentElementId("");
                            puncureChannleMapper.updateByPrimaryKeySelective(puncureChannleEntity);
                        } else {
                            List<PuncureChannleEntity> puncureChannleEntityList = puncureChannleMapper.selectOneByOrderAndBatch(executeDetailDTO.getInpatorderdataId(), executeDetailDTO.getBatchNo());
                            if (CollectionUtils.isNotEmpty(puncureChannleEntityList)) {
                                puncureChannleMapper.deleteByPrimaryKey(puncureChannleEntityList.get(0));
                            }
                        }
                    }
                } else if (VarCodeEnum.JSFS_BZ.getVarCode().equalsIgnoreCase(x.getDataCode())) {
                    //查询出所有相同穿刺点的任务，把所有任务对应的文书中的结束方式改成拔针，并结束任务
                    //输液中心关于此穿刺点下的输液任务流程的界面所有数据都清除

                    //任务执行的不要查出封管的时候通道
                    List<PuncureChannleEntity> list = this.puncureChannleMapper.selectPointListByOrderId2(executeDetailDTO.getInpatorderdataId(), executeDetailDTO.getBatchNo(), "1");
                    List<PuncureChannleEntity> puncureList = this.puncureChannleMapper.selectPointListByOrderId2(executeDetailDTO.getInpatorderdataId(), executeDetailDTO.getBatchNo(), null);
                    //任务处理
                    if (CollectionUtils.isNotEmpty(list)) {
                        if (list.size() != 1) {
                            List<Map<String, Object>> batchList = new CopyOnWriteArrayList<>();
                            list.stream().forEach(y -> {
                                //批量更新文书
                                Map<String, Object> entityMap = new HashMap<>();
                                //判断是否当前节点是否暂停输液，如果是暂停输液，则把其他的文书内容也改成暂停输液
                                //暂时
                                List<OrdersFileIndexDataDTO> dataEntities = fileData.parallelStream().filter(z -> VarCodeEnum.SYZX_SYZT.getVarCode().equalsIgnoreCase(z.getDataCode())).collect(Collectors.toList());
                                if (CollectionUtils.isNotEmpty(dataEntities)) {
                                    this.ordersFileIndexDataMapper.updateXSCZByInpatorderdataId(y.getInpatorderdataId(), y.getBatchNo());
                                }
                                //完成
                                List<OrdersFileIndexDataDTO> dataEntities1 = fileData.parallelStream().filter(z -> VarCodeEnum.SYZX_SYWC.getVarCode().equalsIgnoreCase(z.getDataCode())).collect(Collectors.toList());
                                if (CollectionUtils.isNotEmpty(dataEntities1)) {
                                    //判断如果是当前任务就是输液完成拔针 不是当前任务就是暂停拔针
                                    if (executeDetailDTO.getInpatorderdataId().equals(y.getInpatorderdataId()) && (executeDetailDTO.getBatchNo() + "").equals(y.getBatchNo())) {
                                        this.ordersFileIndexDataMapper.updateSYWCByInpatorderdataId(y.getInpatorderdataId(), y.getBatchNo());
                                    } else {
                                        this.ordersFileIndexDataMapper.updateXSCZByInpatorderdataId(y.getInpatorderdataId(), y.getBatchNo());
                                    }
                                }
                                this.ordersFileIndexDataMapper.updateEmrFileDataByInpatorderdataId(y.getInpatorderdataId(), y.getBatchNo());
                                //2020-11-19输液暂停节点去除，之前的逻辑暂停会先到暂停节点下一步再输液中心，现在暂停直接进入输液中心，继续走下一个节点会找不到任务终止任务，需要过滤掉在输液中心的任务。
                                TaskExecuteBatchEntity taskExecuteBatchEntity = taskExecuteBatchMapper.queryTaskBatchByInpatorderdataIdAndBatchNo(y.getInpatorderdataId(), y.getBatchNo());
                                if (null != taskExecuteBatchEntity) {
                                    //获取要创建下个节点的BatchEntity
                                    taskExecuteBatchEntity.setExecutePersonId(userId);
                                    entityMap.put("taskExecuteDetailEntity", taskExecuteBatchEntity);
                                    entityMap.put("userId", userId);
                                    batchList.add(entityMap);
                                }

                            });
                            if (CollectionUtils.isNotEmpty(batchList)) {
                                nursePatientOrderService.createNextTaskNodeList(batchList, null);
                            }
                            canBZ.set(true);
                        }
                    }
                    //拔针后通道什么
                    if (CollectionUtils.isNotEmpty(puncureList)) {
                        puncureList.stream().forEach(y -> {
                            if (StringUtils.isNotBlank(y.getPunctureChannleId())) {
                                String[] punctureChannleIds = y.getPunctureChannleId().split(",");
                                for (String pId : punctureChannleIds) {
                                    puncureChannleMapper.deleteByPrimaryKey(pId);
                                }
                            }
                        });
                    }
                } else if (VarCodeEnum.SYLC_GHSY.getVarCode().equalsIgnoreCase(x.getDataCode())) {
                    //更换输液，保留穿刺通道信息，结束任务流
                    List<PuncureChannleEntity> list = this.puncureChannleMapper.selectPointListByOrderId(executeDetailDTO.getInpatorderdataId(), executeDetailDTO.getBatchNo());
                    if (CollectionUtils.isNotEmpty(list)) {
                        PuncureChannleEntity puncureChannleEntity = list.get(0);
                        puncureChannleEntity.setSpeedValue("");
                        puncureChannleEntity.setSpeedElementId("");
                        puncureChannleEntity.setShowStatus("0");
                        puncureChannleMapper.updateByPrimaryKeySelective(puncureChannleEntity);
                    }
                }
            });
        }
    }

    private List<EmrFileData> flatConvert2(List<EmrFileData> emrFileDataList) {
        Stack<EmrFileData> stack = new Stack<>();
        List<EmrFileData> dataList = new ArrayList<>();
        for (int i = 0; i < emrFileDataList.size(); i++) {
            EmrFileData topEmrFileData = emrFileDataList.get(i);
            stack.push(topEmrFileData);
            while (!stack.empty()) {
                EmrFileData emrFileData = stack.pop();
                dataList.add(emrFileData);
                List<EmrFileData> subEmrFileDataList = emrFileData.getEmrFileDataList();
                int j = subEmrFileDataList.size();
                while (--j >= 0) {
                    stack.push(subEmrFileDataList.get(j));
                }
            }
        }
        return dataList;
    }

    @Override
    public Result getWaitTasks(String qrCode, int page, int pageSize, String word) {
        String inpatNum = taskExecuteMapper.queryInpatNumByQrcode(qrCode);
        PageHelper.startPage(page, pageSize);
        if (StringUtils.isNotBlank(inpatNum)) {
            List<Map<String, String>> taskList = taskExecuteMapper.queryTasksWithInpatNumAndNodeEnter(inpatNum, NodeEnterEnum.WRISTBAND.getValue(), word);
            PageInfo<Map<String, String>> pageInfo = new PageInfo<>(taskList);
            return ResultGenerator.genOkResult(pageInfo);
        } else {
            // TODO：获取床头卡任务列表
            String bedcard = taskExecuteMapper.queryBedcardByQrcode(qrCode);
            if (StringUtils.isNotBlank(bedcard)) {
                List<Map<String, String>> taskList = taskExecuteMapper.queryTasksWithInpatNumAndNodeEnter(inpatNum, NodeEnterEnum.BEDCARD.getValue(), word);
                PageInfo<Map<String, String>> pageInfo = new PageInfo<>(taskList);
                return ResultGenerator.genOkResult(pageInfo);
            }
        }

        return ResultGenerator.genFailedResult("任务列表获取失败");
    }

    @Override
    public Result checkQrCode(String firstQrCode, String secondQrCode, String nodeType, String showFlag,String uuid) {
        String qrCode = "";
        if (nodeType.equals(NodeEnterEnum.WRISTBAND.getValue())) {
            qrCode = taskExecuteMapper.identifyQrCodeMatch(firstQrCode, secondQrCode, nodeType);
            // 判断是否标本和病人是否一致;
            if (StringUtils.isBlank(qrCode)) {
                //防止扫码2次腕带(标本长度为10)
                //判断扫码的码是否是静配码
                if(!secondQrCode.contains("_") && secondQrCode.length()==14){
                    StaticCenterEntity staticCenterEntity = staticCenterMapper.queryPersonIdByBarCode(secondQrCode, null);
                    if(staticCenterEntity!=null){
                        String staticInpatNum = staticCenterEntity.getInpatNum().split("-")[0];
                        if(!staticInpatNum.equals(firstQrCode)){
                            return ResultGenerator.genFailedResult("患者信息与医嘱信息不匹配！");
                        }
                    }else{
                        return ResultGenerator.genFailedResult("请扫描正确的二维码！");
                    }
                }else if (!secondQrCode.contains("_") && secondQrCode.length() != 10) {
                    return ResultGenerator.genFailedResult("请扫描正确的二维码！");
                }else if (!secondQrCode.contains(firstQrCode) && secondQrCode.length() != 10) {
                    return ResultGenerator.genFailedResult("患者信息与医嘱信息不匹配！");
                }
                Result result = screenQrCode(secondQrCode, "", showFlag);
                if (HttpStatus.OK.value() == result.getCode()) {
                    sendSocketMessage(uuid,firstQrCode);
                    return result;
                }
                String newQrCode = taskExecuteMapper.identifyQrCodeMatch(firstQrCode, secondQrCode, nodeType);
                if (StringUtils.isBlank(newQrCode)) {
                   SpecimenQrCodeStatusDto<TaskNodeVO> specimenResult = specimenService.checkSpecimenQrCode(firstQrCode, secondQrCode, nodeType);
                    if (specimenResult.getSuccess()) {
                        sendSocketMessage(uuid, firstQrCode);
                        return ResultGenerator.genOkResult(specimenResult.getData());
                    } else {
                        return ResultGenerator.genFailedResult(specimenResult.getMsg());
                    }
                }else{
                    qrCode=newQrCode;
                }
            }
        }

        TaskNodeVO taskNodeVO = new TaskNodeVO();
        String taskName = taskExecuteMapper.getTaskNameByQrCode(qrCode);
        taskNodeVO.setNodeType(NodeEnterEnum.NORMAL.getValue());
        taskNodeVO.setNodeTypeName(NodeEnterEnum.NORMAL.getText());
        taskNodeVO.setQrCode(qrCode);
        taskNodeVO.setTaskName(taskName);


        Map<String, String> map = taskExecuteMapper.identifyOrderStatus(qrCode, "");
        if (MapUtils.isNotEmpty(map)) {
            String statusStr = checkOrderStatus(map.get("inpatOrderId"), null);
            if (StringUtils.isNotEmpty(statusStr)) {
                return ResultGenerator.genFailedResult(statusStr);
            }
        }

        NodeInfoDTO nodeInfoDTO = taskExecuteMapper.queryWaitExecuteNode(qrCode);
        if (nodeInfoDTO == null) {
            return ResultGenerator.genFailedResult("未找到任务节点");
        }


        taskNodeVO.setSpecialNodeType(SpecialNodeEnum.NORMAL.getValue());
        taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.NORMAL.getText());
        if (nodeInfoDTO.getNodeId().equals(SpecialNodeEnum.NEWINFLUSION.getNodeId())) {
            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.NEWINFLUSION.getValue());
            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.NEWINFLUSION.getText());
        }
        if (ConstsEnum.TASK_NAME_WHLC.getName().equals(taskName)) {
            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.WHLC.getValue());
            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.WHLC.getText());
        } else if (ConstsEnum.TASK_NAME_CNYY.getName().equals(taskName)) {
            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.CNYY.getValue());
            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.CNYY.getText());
        }
        // 查询qrCode关联的所有医嘱
        Map<String, String> ordersMap = taskExecuteMapper.queryQrInpatNumNoNode(qrCode);
        if (MapUtils.isEmpty(ordersMap)) {
            return ResultGenerator.genFailedResult("无当前类型任务需要执行");
        }

        // 根据用户病区获取指定病区的
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");

        // TODO: 目前只做了病区判断，后面需要根据具体节点具体权限范围设置进行判断
//        String resultInpatNum = taskExecuteMapper.identifyAuthority(userId, map.get("inpatNum"));
//        if (StringUtils.isBlank(resultInpatNum)) {
//            return ResultGenerator.genFailedResult("您无权操作该任务");
//        }

        PatientInfo patientInfo = new PatientInfo();
        patientInfo.setMedicalNum(nodeInfoDTO.getMedicalNum());
        patientInfo.setBedNo(nodeInfoDTO.getBedNo());
        patientInfo.setBedLabel(nodeInfoDTO.getBedLabel());
        patientInfo.setSex(nodeInfoDTO.getSex());
        patientInfo.setAge(computeAge(nodeInfoDTO));
        patientInfo.setPatName(nodeInfoDTO.getPatName());
        taskNodeVO.setPatientInfo(patientInfo);
        taskNodeVO.setTaskNodeId(nodeInfoDTO.getTaskNodeId());
        taskNodeVO.setNodeName(nodeInfoDTO.getNodeName());
        List<OrderInfo> orderInfoList = taskExecuteMapper.queryOrderInfos(nodeInfoDTO.getInpatOrderId(), nodeInfoDTO.getInpatNum());
        taskNodeVO.setOrderInfoList(orderInfoList);
        String orderInfoFreq = taskExecuteMapper.queryOrderInfoFreq(nodeInfoDTO.getInpatOrderId());
        orderInfoList.get(0).setFreq((org.apache.commons.lang3.StringUtils.isBlank(orderInfoList.get(0).getFreq()) ? "" : orderInfoList.get(0).getFreq()) + " " + (org.apache.commons.lang3.StringUtils.isBlank(orderInfoFreq) ? "" : orderInfoFreq));
        try {
            //暂时先用这种方法处理执行时间，后续如果其他类型也需要这样显示 需要另外想方法
            String[] qrCodes = qrCode.split("_");
            String executeTimeStr = qrCodes[1].substring(qrCodes[1].length() - 14);
            Date executeTime = DateUtil.stringToDate(executeTimeStr, "yyyyMMddHHmmss");
            String execTimeStr = DateUtil.dateToString(executeTime, "yyyy-MM-dd HH:mm:ss");
            taskNodeVO.setExecTime(execTimeStr);
        } catch (Exception e) {
            taskNodeVO.setExecTime(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        }
        if (StringUtils.isNotBlank(nodeInfoDTO.getEmrFileId())) {
            EmrFile emrFile = fileIndexService.getFileIndex(nodeInfoDTO.getEmrFileId());
            List<EmrFileData> flatList = flatConvert2(emrFile.getEmrFileDataList());
            if (ConstsEnum.TASK_NAME_JMZS.getName().equals(taskName) || ConstsEnum.TASK_NAME_PNZS.getName().equals(taskName) || ConstsEnum.TASK_NAME_PXZS.getName().equals(taskName) || ConstsEnum.TASK_NAME_DSY.getName().equals(taskName) || ConstsEnum.TASK_NAME_YDS.getName().equals(taskName)) {
                //皮内注射不需要新增穿刺，过滤新增穿刺节点
                if (ConstsEnum.TASK_NAME_PNZS.getName().equals(taskName)) {
                    taskNodeVO.setSpecialNodeType(SpecialNodeEnum.PNZS.getValue());
                    taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.PNZS.getText());
//                    taskNodeVO.setNodeName(SpecialNodeEnum.PNZS.getText());
                    flatList.stream().filter(fileData -> VarCodeEnum.SYLK_SYRK.getVarCode().equals(fileData.getElement().getVarCode())).forEach(obj -> {
                        obj.getFileIndexDataEntity().setShowIdentification(ConstsEnum.DEFAULT_YES.getName());//是否显示 1-不显示
                    });
                }
                if (ConstsEnum.TASK_NAME_PXZS.getName().equals(taskName)) {
                    taskNodeVO.setSpecialNodeType(SpecialNodeEnum.PXZS.getValue());
                    taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.PXZS.getText());
                }
                if (ConstsEnum.TASK_NAME_DSY.getName().equals(taskName)) {
                    taskNodeVO.setSpecialNodeType(SpecialNodeEnum.DSY.getValue());
                    taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.DSY.getText());
                }
                if (ConstsEnum.TASK_NAME_YDS.getName().equals(taskName)) {
                    taskNodeVO.setSpecialNodeType(SpecialNodeEnum.YDS.getValue());
                    taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.YDS.getText());
                }
                boolean flag = false;
                String drugName = "";
                Result result = new Result();
                CheckForNurseDTO dto = new CheckForNurseDTO();
                try {
                    dto.setInpatNum(nodeInfoDTO.getInpatNum());
                    dto.setUserId(userId);
                    dto.setOrderIds(Collections.singletonList(nodeInfoDTO.getInpatOrderId()));
                    result = patientOrderService.checkForNurse(dto);
                    if (result.getCode() == HttpStatus.OK.value()) {
                        Map infoMap = JSONObject.parseObject(JSON.toJSONString(result.getData()), Map.class);
                        if (infoMap != null && infoMap.get(nodeInfoDTO.getInpatOrderId()) != null) {
                            List<Info> infos = JSON.parseArray(JSON.toJSONString(infoMap.get(nodeInfoDTO.getInpatOrderId())), Info.class);
                            if (!CollectionUtils.isEmpty(infos)) {
                                for (Info info : infos) {
                                    if ("过敏".equals(info.getType())) {
                                        flag = true;
                                        drugName = info.getDrugName();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("判断过敏调用医生站出错,CheckForNurseDTO:{},result：{}", dto, result, e);
                }
                //查询入院记录过敏药物
                //TODO 与智慧药学对接
//                String badDrugs = emrFileMapper.findBadDrugs(ordersMap.get("inpatNum"));
//                if (StringUtils.isNotBlank(badDrugs)) {
//                    String orderDrug = orderInfoList.stream().map(OrderInfo::getOrdersItem).collect(Collectors.joining(","));
//                    List<String> badDrug = Arrays.asList(badDrugs.split(","));
//                    for (int i = 0; i < badDrug.size(); i++) {
//                        if (orderDrug.contains(badDrug.get(i))) {
//                            flag = true;
//                            drugName = badDrug.get(i);
//                            break;
//                        }
//                    }
//                }
                if (flag) {
                    taskNodeVO.setDrugName(drugName);
                    flatList.stream().filter(fileData -> VarCodeEnum.SFZZ.getVarCode().equals(fileData.getElement().getVarCode()) || VarCodeEnum.SFYWGM.getVarCode().equals(fileData.getElement().getVarCode())).forEach(obj -> {
                        Map<String, String> trueMap = emrFileMapper.findTrueFlag(obj.getElement().getId(), ConstsEnum.DEFAULT_YES.getName());
                        obj.getFileIndexDataEntity().setDataCode(trueMap.get("dataCode"));
                        obj.getFileIndexDataEntity().setDataValue(trueMap.get("dataValue"));
                    });
                }
            } else if (ConstsEnum.TASK_NAME_CNYY.getName().equals(taskName)) {
                String preEmrFileId = taskExecuteBatchMapper.getPreEmrFileId(secondQrCode);
                EmrFile preEmrFile = fileIndexService.getFileIndex(preEmrFileId);
                if (preEmrFile != null) {
                    List<EmrFileData> pre = flatConvert2(preEmrFile.getEmrFileDataList());
                    pre.stream().filter(fileData -> VarCodeEnum.YLGMC.getVarCode().equals(fileData.getElement().getVarCode())).forEach(obj -> {
                        flatList.stream().filter(fileData -> VarCodeEnum.YLGMC.getVarCode().equals(fileData.getElement().getVarCode())).forEach(preObj -> {
                            preObj.getFileIndexDataEntity().setDataValue(obj.getFileIndexDataEntity().getDataValue());
                            preObj.getFileIndexDataEntity().setDataCode(obj.getFileIndexDataEntity().getDataCode());
                        });
                    });
                    pre.stream().filter(fileData -> VarCodeEnum.CNYY_YQSY.getVarCode().equals(fileData.getElement().getVarCode())).forEach(obj -> {
                        flatList.stream().filter(fileData -> VarCodeEnum.CNYY_YQSY.getVarCode().equals(fileData.getElement().getVarCode())).forEach(preObj -> {
                            preObj.getFileIndexDataEntity().setDataValue(obj.getFileIndexDataEntity().getDataValue());
                            preObj.getFileIndexDataEntity().setDataCode(obj.getFileIndexDataEntity().getDataCode());
                        });
                    });
                }
            }

            taskNodeVO.setEmrFile(emrFile);
        }
        sendSocketMessage(uuid,firstQrCode);
        return ResultGenerator.genOkResult(taskNodeVO);
    }

    @Value("${socket.url}")
    private String socketUrl;

    public void sendSocketMessage(String uuid, String secondQrCode) {
        String interval = taskExecuteMapper.getVarValueByVarCode("nurse_inpatnum_interval");
        Map<String,Object> data = new HashMap<>();
        data.put("inpatNum",secondQrCode);
        data.put("interval",interval);
        PushSocketMessage pushSocketMessage = new PushSocketMessage();
        SocketMessageDTO socketMessageDTO = new SocketMessageDTO();
        socketMessageDTO.setData(data);
        socketMessageDTO.setReceiver(uuid);
        socketMessageDTO.setMsgType("refresh");
        pushSocketMessage.setUserIds(Collections.singletonList(uuid));
        pushSocketMessage.setData(socketMessageDTO);
        HttpClientUtil.sendPost(socketUrl, pushSocketMessage);
    }

    @Override
    public Result ruleFilter(String emrFileId, String varCode, String dataCode, String dataValue) {
//        String tplId = taskExecuteMapper.queryTplByEmrFileId(emrFileId);
//        if (tplId.equals(SpecialTplEnum.NEWINFLUSION.getValue()) || tplId.equals(SpecialTplEnum.INFLUSION_AROUND.getValue())) {
        // 输液滴速触发规则
        if (varCode.equals(StateEnum.INFLUSION_SPEED.getValue())) {
            int sum = 0;
            // 如果剩余量有值，那么根据时间和滴速计算当前剩余量，如果剩余量无值，获取医嘱药品总剂量作为剩余量
            // 获取当前文书滴速和剩余量
            // 获取剩余量
            Map<String, String> surPlusMap = taskExecuteMapper.queryFileIndexDataMap(emrFileId, StateEnum.INFLUSION_SURPLUS.getValue());
            if (surPlusMap.get("dataValue") == null) { // 剩余量为空
                //根据文书ID获取当前病人入院号
                String inpatNum = transfusionMapper.getInpatNum(emrFileId);
                //根据文书ID获取当前任务流程ID
                String taskExecuteId = transfusionMapper.queryTaskExecuteId(emrFileId);
                //根据当前任务流程ID和入院号，获取当前输液医嘱信息
                List<Map<String, String>> drugList = transfusionMapper.queryDurgsByOrderNo(inpatNum, taskExecuteId);
                for (Map<String, String> map : drugList) {
                    //获取当前医嘱中单位为ML的剂量值并累加
                    if ("ml".equalsIgnoreCase(map.get("unit"))) {
                        sum += Integer.parseInt(map.get("itemDosage"));
                    }
                }
                Map resultMap = new HashMap();
                resultMap.put("dataValue", String.valueOf(sum));
                resultMap.put("dataCode", "");
                resultMap.put("varCode", StateEnum.INFLUSION_SURPLUS.getValue());
                return ResultGenerator.genOkResult(resultMap);
            } else {
                Float surPlusFloat = Float.parseFloat(surPlusMap.get("dataValue"));
                Map<String, String> speedMap = taskExecuteMapper.queryFileIndexDataMap(emrFileId, StateEnum.INFLUSION_SPEED.getValue());
                Float speedFloat = Float.parseFloat(speedMap.get("dataValue") == null ? "0" : speedMap.get("dataValue"));
                if (speedMap.get("unit") != null && speedMap.get("unit").equals("滴/分钟")) {
                    Float perDropValume = 1f / 20; // 1滴相当于1/20ml
                    Float valumeOfPerSecond = speedFloat / 60; // 每秒滴数
                    long subSconds = (new Date().getTime() - DateUtil.stringToDate(speedMap.get("modifyTime")).getTime()) / 1000; // 当前时间和剩余量更新时间的差值
                    float useValume = valumeOfPerSecond * subSconds * perDropValume;
                    Map resultMap = new HashMap();
                    if (useValume <= surPlusFloat) {
                        resultMap.put("dataValue", String.valueOf(surPlusFloat - useValume));
                    } else {
                        resultMap.put("dataValue", "0");
                    }
                    resultMap.put("dataCode", "");
                    resultMap.put("varCode", StateEnum.INFLUSION_SURPLUS.getValue());
                    return ResultGenerator.genOkResult(resultMap);
                }
            }
        }

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result workSpaceScreen(String qrCode, String nodeId) {

        /*if (!generatTaskByQrcode(qrCode)) {
            return ResultGenerator.genFailedResult("任务执行中，请重试");
        }*/
        boolean genBoolean = false;
        //根据预生成的qrcode，生成实际的任务批次
        Result genResult = generatTaskByQrcode(qrCode);
        if(genResult.getCode() == 400){
            return genResult;
        }else{
            genBoolean=true;
        }
        Map<String, String> orderStatus = taskExecuteMapper.identifyOrderStatus(qrCode, "");
        if (MapUtils.isNotEmpty(orderStatus)) {
            if (orderStatus.get("cancelDatetime") != null) {
                return ResultGenerator.genFailedResult("该医嘱已取消");
            }

//            if (orderStatus.get("planEndDatetime") != null && DateUtil.stringToDate(orderStatus.get("planEndDatetime")).getTime() < new Date().getTime()) {
//                return ResultGenerator.genFailedResult("该医嘱已停止");
//            }

//			if (orderStatus.get("confirmDatetime") == null || (!orderStatus.get("confirmDatetime").equals(orderStatus.get("createDatetime")) && !orderStatus.get("confirmDatetime").equals(DateUtil.dateToString(DateUtil.getDateBefore(new Date(), 1), "yyyy-MM-dd")))) {
//				return ResultGenerator.genFailedResult("医嘱尚未确认，无法执行");
//			}
        }

        // 查询qrCode关联的所有医嘱
        Map<String, String> map = taskExecuteMapper.queryQrInpatNumByNode(qrCode, nodeId);
        if (MapUtils.isEmpty(map)) {
            return ResultGenerator.genFailedResult("无当前类型任务需要执行");
        }

        // 根据用户病区获取指定病区的
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");

        // TODO: 目前只做了病区判断，后面需要根据具体节点具体权限范围设置进行判断
        String resultInpatNum = taskExecuteMapper.identifyAuthority(userId, map.get("inpatNum"));
//        if (StringUtils.isBlank(resultInpatNum)) {
//            return ResultGenerator.genFailedResult("您无权操作该任务");
//        }

        String inpatNum = map.get("inpatNum");
        String inpatOrderId = map.get("inpatOrderId");
        if (StringUtils.isBlank(inpatNum)) {
            return ResultGenerator.genFailedResult("获取病人信息失败");
        }

        // 根据住院号和qrCode获取所有组内医嘱
        List<String> inpatOrderIds = taskExecuteMapper.queryInpatOrderIds(inpatNum, inpatOrderId);
        if (ArrayUtils.isEmpty(inpatOrderIds.toArray())) {
            inpatOrderIds = new ArrayList<>();
            inpatOrderIds.add(inpatOrderId);
        }
        //查询该Qrcode对应的医嘱信息中保存的病人信息，包括床号，入院号，姓名，用法（administration关联查询hsp_basic_data_value表中的data_value），医嘱开立时间
        //获取医嘱中病人信息
        Map<String, String> patientInfo = patientMapper.queryPatientInfo(inpatNum);

        // 根据医嘱获取医嘱所有子医嘱药品
        List<Map<String, String>> drugList = taskExecuteMapper.queryOrderDrugs(inpatOrderIds, inpatNum);

        //将查询结果拼接为前台需要的数据（床号，病案号，姓名，药品及剂量集合，用法，开立时间）
        OrderDrugsByQrcodeDTO orderDrugsByQrcodeDTO = new OrderDrugsByQrcodeDTO();
        orderDrugsByQrcodeDTO.setBedNo(patientInfo.get("bedNo"));
        orderDrugsByQrcodeDTO.setBedLabel(patientInfo.get("bedLabel"));
        orderDrugsByQrcodeDTO.setMedicalNum(patientInfo.get("medicalNum"));
        orderDrugsByQrcodeDTO.setPatName(patientInfo.get("patName"));
        orderDrugsByQrcodeDTO.setQrCode(qrCode);
        orderDrugsByQrcodeDTO.setDrugList(drugList);
        orderDrugsByQrcodeDTO.setAdministrtion(drugList.get(0).get("administration"));
        orderDrugsByQrcodeDTO.setPlanBeginTime(drugList.get(0).get("planBeginDatetime")); // 这个任务开始日期应该根据任务流第一个节点日期获取
        return ResultGenerator.genOkResult(orderDrugsByQrcodeDTO);
    }

    @Override
    public Result getWorkLog(String inpatNum, String dateTime, int page, int pageSize, String search, String type, String orderType) {
        //PageHelper.startPage(page, pageSize);

        //List<Map<String, String>> list2 = taskExecuteMapper.queryExecuteDetailWorkLog(inpatNum, dateTime, search, type);

        List<Map<String, Object>> list = new CopyOnWriteArrayList<>();
        //List<Map<String, String>> list = taskExecuteMapper.queryExecuteDetailWorkLog(inpatNum, dateTime, search, type);
        /*治疗单  treatment
          服药单  medication
          注射单  injection
          其他给药单  other
          雾化单  atomization
          肠内营养  nutrition
          输液单  infusion
          标本采集   specimen
          检查       inspect
         */
        //检查
        //检验流程-标本采集
        List<String> orderTypeList = new CopyOnWriteArrayList<>();
        if ("all".equals(orderType) || orderType.indexOf("specimen") >= 0) {
            orderTypeList.add("检验流程");
        }
        if ("all".equals(orderType) || orderType.indexOf("inspect") >= 0) {
            orderTypeList.add("检查流程");
        }
        if (CollectionUtils.isNotEmpty(orderTypeList)) {
            List<Map<String, Object>> taskList1 = taskExecuteMapper.selectSpecimenAndInspectWorkLog1(type, inpatNum, dateTime, orderTypeList);
            List<Map<String, Object>> taskList2 = taskExecuteMapper.selectSpecimenAndInspectWorkLog2(type, inpatNum, dateTime, orderTypeList);
            //检验
            if (CollectionUtils.isNotEmpty(taskList1)) {
                for (Map<String, Object> map : taskList1) {
                    map.put("drugList", new ArrayList<Map<String, String>>());
                    String inpatorderdataId = (String) map.get("inpatorderdata_id");
                    String inpatorderdataIds[] = inpatorderdataId.split(",");
                    if (inpatorderdataId != null && inpatorderdataId.length() > 0) {
                        List<Map<String, Object>> batchList = taskExecuteMapper.queryTaskExecuteBatchByInpatorderdataId(inpatorderdataIds[0], null);
                        map.put("infusionExecutionList", batchList.stream().filter(s -> "1".equals(s.get("status"))).collect(Collectors.toList()));
                        map.put("inpatorderdataIds", "");
                        if("检验流程".equals(map.get("taskName"))){
                            if (CollectionUtils.isNotEmpty(batchList)) {
                                List<Map<String, Object>> collectionExecutionMap = batchList.stream().filter(s -> "0".equals(s.get("status"))).collect(Collectors.toList());
                                if (CollectionUtils.isNotEmpty(collectionExecutionMap)) {
                                    Map<String, String> collectionMap = orderMapper.selectCollectionTime(inpatorderdataIds[0]);
                                    if(collectionMap!=null){
                                        map.put("status", "1");
                                    }else{
                                        map.put("status", "0");
                                    }
                                }else{
                                    map.put("status", "2");
                                }
                            }
                        }
                    }

                }
                list.addAll(taskList1);
            }
            if (CollectionUtils.isNotEmpty(taskList2)) {
                for (Map<String, Object> map : taskList2) {
                    map.put("drugList", new ArrayList<Map<String, String>>());
                    String inpatorderdataId = (String) map.get("inpatorderdata_id");
                    String inpatorderdataIds[] = inpatorderdataId.split(",");
                    if (inpatorderdataId != null && inpatorderdataId.length() > 0) {
                        List<Map<String, Object>> batchList = taskExecuteMapper.queryTaskExecuteBatchByInpatorderdataId(inpatorderdataIds[0], null);
                        map.put("infusionExecutionList", batchList.stream().filter(s -> "1".equals(s.get("status"))).collect(Collectors.toList()));
                        map.put("inpatorderdataIds", "");
                        if("检验流程".equals(map.get("taskName"))){
                            if (CollectionUtils.isNotEmpty(batchList)) {
                                List<Map<String, Object>> collectionExecutionMap = batchList.stream().filter(s -> "0".equals(s.get("status"))).collect(Collectors.toList());
                                if (CollectionUtils.isNotEmpty(collectionExecutionMap)) {
                                    Map<String, String> collectionMap = orderMapper.selectCollectionTime(inpatorderdataIds[0]);
                                    if(collectionMap!=null){
                                        map.put("status", "1");
                                    }else{
                                        map.put("status", "0");
                                    }
                                }else{
                                    map.put("status", "2");
                                }
                            }
                        }
                    }
                }
                list.addAll(taskList2);
            }
        }

        if ("all".equals(orderType) || orderType.indexOf("medication") >= 0) {
            if ("0".equals(type) || "1".equals(type)) {
                //口服药流程
                //待摆药 （未完成）
                List<Map<String, Object>> byList = this.getByList(inpatNum, null, dateTime, search, OralEnum.BY_NODE.getName(), "服药", "0", null);
                //待给药 （未完成）
                List<Map<String, Object>> doseList = this.getRelationList(null, dateTime, search, OralEnum.GY_NODE.getName(), null, inpatNum, "服药", "0");
                //待服药 （未完成）
                List<Map<String, Object>> waitTakeMedicineList = this.getRelationList(null, dateTime, search, OralEnum.FY_NODE.getName(), null, inpatNum, "服药", "0");
                list.addAll(byList);
                list.addAll(doseList);
                list.addAll(waitTakeMedicineList);
            }
            if ("0".equals(type) || "2".equals(type)) {
                //已终止 (已完成)
                List<Map<String, Object>> returnList = this.getReturnList(inpatNum, dateTime, search, "服药", "2");
                //已服药 (已完成)
                List<Map<String, Object>> taken = this.getRelationList(null, dateTime, search, OralEnum.WC_NODE.getName(), null, inpatNum, "服药", "2");
                list.addAll(returnList);
                list.addAll(taken);
            }
        }
        //输液流程-非静配
        if ("all".equals(orderType) || orderType.indexOf("infusion") >= 0) {
            List<Map<String, Object>> infusionList = this.getInfusionList(inpatNum, dateTime, search, "a4c7fd2d1a984441a924c3fc00b83ae8", "输液", "1");
            //已完成
            if ("2".equals(type)) {
                infusionList = infusionList.stream().filter(infusion -> "2".equals(infusion.get("status").toString())).collect(Collectors.toList());
            } else if ("1".equals(type)) {
                infusionList = infusionList.stream().filter(infusion -> ("0".equals(infusion.get("status").toString()) || "1".equals(infusion.get("status").toString()))).collect(Collectors.toList());
            }

            if (CollectionUtils.isNotEmpty(infusionList)) {
                list.addAll(infusionList);
            }
            //输液流程-静配
            List<Map<String, Object>> intravenousInfusionList = this.getInfusionList(inpatNum, dateTime, search, "a4c7fd2d1a984441a924c3fc00b83ae8", "输液", "2");
            //已完成
            if ("2".equals(type)) {
                intravenousInfusionList = intravenousInfusionList.stream().filter(infusion -> "2".equals(infusion.get("status").toString())).collect(Collectors.toList());
            } else if ("1".equals(type)) {
                intravenousInfusionList = intravenousInfusionList.stream().filter(infusion -> ("0".equals(infusion.get("status").toString()) || "1".equals(infusion.get("status").toString()))).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(intravenousInfusionList)) {
                list.addAll(intravenousInfusionList);
            }
        }
        //注射
        //雾化 atomization
        //治疗 treatment
        List<String> orderTypeLists = new CopyOnWriteArrayList<>();
        if ("all".equals(orderType) || orderType.indexOf("treatment") >= 0) {
            orderTypeLists = new CopyOnWriteArrayList<>();
            orderTypeLists.add("273e0497392049b092736c6f9e9971f9");
            List<Map<String, Object>> infusionList = this.getAtomizationList(inpatNum, dateTime, search, orderTypeLists, "治疗", "0");
            if ("2".equals(type)) {
                infusionList = infusionList.stream().filter(infusion -> "2".equals(infusion.get("status").toString())).collect(Collectors.toList());
            } else if ("1".equals(type)) {
                infusionList = infusionList.stream().filter(infusion -> ("0".equals(infusion.get("status").toString()) || "1".equals(infusion.get("status").toString()))).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(infusionList)) {
                list.addAll(infusionList);
            }
        }
        if ("all".equals(orderType) || orderType.indexOf("atomization") >= 0) {
            orderTypeLists = new CopyOnWriteArrayList<>();
            orderTypeLists.add("77cab220c65f4c37ae127c7639790118");
            List<Map<String, Object>> infusionList = this.getAtomizationList(inpatNum, dateTime, search, orderTypeLists, "雾化", "0");
            if ("2".equals(type)) {
                infusionList = infusionList.stream().filter(infusion -> "2".equals(infusion.get("status").toString())).collect(Collectors.toList());
            } else if ("1".equals(type)) {
                infusionList = infusionList.stream().filter(infusion -> ("0".equals(infusion.get("status").toString()) || "1".equals(infusion.get("status").toString()))).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(infusionList)) {
                list.addAll(infusionList);
            }
        }
        //注射
        if ("all".equals(orderType) || orderType.indexOf("injection") >= 0) {
            orderTypeLists = new CopyOnWriteArrayList<>();
            orderTypeLists.add("3b1e0c146d314aa18aaa54f7c382af19");
            List<Map<String, Object>> infusionList = this.getAtomizationList(inpatNum, dateTime, search, orderTypeLists, "注射", "0");
            if ("2".equals(type)) {
                infusionList = infusionList.stream().filter(infusion -> "2".equals(infusion.get("status").toString())).collect(Collectors.toList());
            } else if ("1".equals(type)) {
                infusionList = infusionList.stream().filter(infusion -> ("0".equals(infusion.get("status").toString()) || "1".equals(infusion.get("status").toString()))).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(infusionList)) {
                list.addAll(infusionList);
            }
        }
        //肠内营养  nutrition
        if ("all".equals(orderType) || orderType.indexOf("nutrition") >= 0) {
            orderTypeLists = new CopyOnWriteArrayList<>();
            orderTypeLists.add("0cb6d01c364c4cd2a6ddbd9235bd42c9");
            List<Map<String, Object>> infusionList = this.getAtomizationList(inpatNum, dateTime, search, orderTypeLists, "肠内营养", "0");
            if ("2".equals(type)) {
                infusionList = infusionList.stream().filter(infusion -> "2".equals(infusion.get("status").toString())).collect(Collectors.toList());
            } else if ("1".equals(type)) {
                infusionList = infusionList.stream().filter(infusion -> ("0".equals(infusion.get("status").toString()) || "1".equals(infusion.get("status").toString()))).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(infusionList)) {
                list.addAll(infusionList);
            }
        }
        //其他给药单  other
        /*if ("all".equals(orderType) || orderType.indexOf("other") >= 0) {
            orderTypeLists = new CopyOnWriteArrayList<>();
            orderTypeLists.add("fa09fa05e36d488d8ca7c3c8205a78ed");
            List<Map<String, Object>> infusionList = this.getAtomizationList(inpatNum, dateTime, search, orderTypeLists, "其他给药", "0");
            if ("2".equals(type)) {
                infusionList = infusionList.stream().filter(infusion -> "2".equals(infusion.get("status").toString())).collect(Collectors.toList());
            } else if ("1".equals(type)) {
                infusionList = infusionList.stream().filter(infusion -> ("0".equals(infusion.get("status").toString()) || "1".equals(infusion.get("status").toString()))).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(infusionList)) {
                list.addAll(infusionList);
            }
        }*/
        int totalLength = 0;
        //排序
        if (CollectionUtils.isNotEmpty(list)) {
            list = list.stream().sorted(Comparator.comparing(TaskExecuteServiceImpl::comparingByStatus)
                    .thenComparing(TaskExecuteServiceImpl::comparingByExecutionTime))
                    .collect(Collectors.toList());
            totalLength = list.size();

            if (page != 0 && pageSize != 0) {
                list = list.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
            }
        }

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(totalLength);
        return ResultGenerator.genOkResult(pageInfo);
    }

    private static String comparingByStatus(Map<String, Object> map) {
        return String.valueOf(map.get("status"));
    }

    private static String comparingByExecutionTime(Map<String, Object> map) {
        return String.valueOf(map.get("executionTime"));
    }

    /**
     * 待摆药
     *
     * @param inpatNum
     * @param freq
     * @param date
     * @param keyWord
     * @param nodeId
     * @return
     */
    List<Map<String, Object>> getByList(String inpatNum, String freq, String date, String keyWord, String nodeId, String nodeName, String status, String freqTime) {
        long time1 = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
        String formatDate = "";
        try {
            formatDate = sdf.format(sdf3.parse(date));
        } catch (Exception e) {
            log.error("时间解析错误");
        }
        String freqDeal = "";
        if (StringUtils.isNotBlank(freq)) {
            freqDeal = freq.substring(0, 2);
            if (freqDeal.indexOf("0") == 0) {
                freqDeal = freqDeal.substring(1, 2);
            }
        }
        SimpleDateFormat hSdf = new SimpleDateFormat("HH");
        String hour = hSdf.format(new Date(new Date().getTime() + (1000 * 60 * 60)));
        hour += ":00:00";
        if (null == freq) {
            freq = "-1";
        } else if (freq.equals("-1")) {
            freq = hour;
        }

        List<OralMedicineListDTO> result = new ArrayList();
        Result oral = getMedicineListByApp(freq, date, "0", keyWord, inpatNum);
        List<OralMedicineListDTO> oralList = (List<OralMedicineListDTO>) oral.getData();
        System.out.println("-----------------------------口服药耗时列表查询:" + (System.currentTimeMillis() - time1));
        Set<String> freqTimeSet = new LinkedHashSet<>();
        for (OralMedicineListDTO oralMap : oralList) {
            freqTimeSet.add(oralMap.getFreqData());
            if (StringUtils.isNotEmpty(freqTime)) {
                if (!freqTime.equals(oralMap.getFreqData())) {
                    continue;
                }
            }
            String exTime = DateUtil.dateToString(DateUtil.stringToDate(oralMap.getOralCode().
                    substring(oralMap.getOralCode().length() - 12, oralMap.getOralCode().length()), "yyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss");

            List<OralMedicineListDTO> orders = new ArrayList();//除摆药未扫码外的LIST
            List<Map<String, String>> relationList = oralMedicineMapper.getRelationList(null, null, null, null, oralMap.getOralCode(), null, null, inpatNum);
            if (relationList != null && relationList.size() > 0) {//如果有关系表,则已经入摆药,无需生成关系
                for (Map<String, String> relation : relationList) {
                    if (oralMap.getInpatNum().equals(relation.get("inpatNum")) && oralMap.getFreqData().equals(relation.get("freqData"))) {
                        OralMedicineListDTO resItem = new OralMedicineListDTO();
                        resItem.setDrugName(relation.get("drugName"));
                        resItem.setSpec(relation.get("spec"));
                        resItem.setItemDosage(relation.get("itemDosage") + relation.get("unit"));
                        resItem.setUnit(relation.get("unit"));
                        resItem.setInpatorderdataId(relation.get("inpatorderdataId"));
                        if (StringUtils.isNotBlank(relation.get("remark"))) {
                            resItem.setRemark(relation.get("remark"));
                        }
                        resItem.setInpatNo(relation.get("inpatNum").split(",")[0]);
                        resItem.setOrderNo(relation.get("orderNo"));
                        resItem.setDosageBasicUnit(relation.get("dosageBasicUnit"));
                        resItem.setMachineSign(relation.get("machineSign"));
                        oralMap.setRemark(relation.get("remark"));
                        oralMap.setInpatNo(oralMap.getMedicalNum());
                        oralMap.setOralCode(relation.get("qrCode"));
                        if (OralEnum.BY_NODE.getName().equals(relation.get("nodeId"))) {
                            orders.add(resItem);
                        }
                    } else {
                        if (StringUtils.isNotBlank(oralMap.getDrugList().get(0).getRemark())) {
                            oralMap.setRemark(oralMap.getDrugList().get(0).getRemark());
                        }
                        oralMap.setInpatNo(oralMap.getMedicalNum());
//                        oralMap.setItemDosage(oralMap.getItemDosage()+oralMap.getUnit());
                    }
                }
                if (orders != null && orders.size() > 0) {
                    oralMap.setDrugList(orders);
                }
            } else {
                List<OralMedicineListDTO> checkList = new CopyOnWriteArrayList();
                oralMap.getDrugList().stream().forEach(item -> {
                    String checkFlag = oralMedicineMapper.checkTermination(item.getInpatNum(), item.getInpatorderdataId(), date, item.getFreqData());
                    if (checkFlag == null) {
                        checkList.add(item);
                    }
                });
                oralMap.setInpatNo(oralMap.getMedicalNum());
                oralMap.setDrugList(checkList);
                if (checkList == null) {
                    orders.addAll(new ArrayList());
                } else {
                    orders.addAll(checkList);
                }
            }
            oralMap.setExecutionTime(exTime);
            if (orders != null && orders.size() > 0) {
                result.add(oralMap);
            }
        }
        System.out.println("-----------------------------口服药耗时关系表查询:" + (System.currentTimeMillis() - time1));
        int total = result.size();

        List<Map<String, Object>> lastList = new CopyOnWriteArrayList<>();
        if (CollectionUtils.isNotEmpty(result)) {
            for (OralMedicineListDTO medicineListDTO : result) {
                Map<String, Object> inpatres = new HashMap<>();//一条数据
                if (StringUtils.isNotBlank(medicineListDTO.getBedNo())) {
                    inpatres.put("bedNo", medicineListDTO.getBedNo());
                } else {
                    inpatres.put("bedNo", "0");
                }
                inpatres.put("nodeName", nodeName);
                inpatres.put("inpatNum", medicineListDTO.getInpatNum());
                inpatres.put("inpatNo", medicineListDTO.getMedicalNum());
                inpatres.put("administration", medicineListDTO.getAdministration());
                inpatres.put("patName", medicineListDTO.getPatName());
                inpatres.put("remark", medicineListDTO.getRemark());
                inpatres.put("sex", medicineListDTO.getSex());
                inpatres.put("oralCode", medicineListDTO.getOralCode());
                inpatres.put("qrCode", medicineListDTO.getQrCode());
                inpatres.put("freqData", medicineListDTO.getFreqData());
                inpatres.put("executionTime", medicineListDTO.getExecutionTime());
                medicineListDTO.getDrugList().sort((a, b) -> new BigDecimal(a.getOrderNo()).intValue() - new BigDecimal(b.getOrderNo()).intValue());
                inpatres.put("drugList", medicineListDTO.getDrugList());
                inpatres.put("status", status);
                List<Map<String, Object>> infusionExecutionList = new CopyOnWriteArrayList<>();
                inpatres.put("infusionExecutionList", infusionExecutionList);
                inpatres.put("inpatorderdataIds", StringUtils.join(medicineListDTO.getDrugList().stream().map(OralMedicineListDTO::getInpatorderdataId).collect(Collectors.toList()), ","));
                lastList.add(inpatres);
            }
        }

        lastList.sort((a, b) -> Integer.parseInt(a.get("bedNo").toString() + new BigDecimal(a.get("executionTime").toString().substring(8, 16).replaceAll("-", "").replaceAll(" ", "").replaceAll(":", ""))) -
                Integer.parseInt(b.get("bedNo").toString() + new BigDecimal(b.get("executionTime").toString().substring(8, 16).replaceAll("-", "").replaceAll(" ", "").replaceAll(":", ""))));

        return lastList;
    }

    public Result getMedicineListByApp(String freq, String date, String print, String keyWord, String inpatList) {
        //口服药条码生成任务
        String executeDateStr = date.replaceAll("-", "");
        Date executeDate = DateUtil.stringToDate(executeDateStr, "yyyyMMdd");
        Date executeEndDateTime = DateUtil.getDateAfter(DateUtil.stringToDate(executeDateStr, "yyyyMMdd"), 1);
        String[] inpats = inpatList.split(",");
        if (inpatList.equals("")) {
            inpats = null;
        }
        //查询指定时间、查询间隔时间
        List<OralMedicineListDTO> orderExecs = oralMedicineMapper.selectOralByInpatsByApp(inpats, executeDate, "-1", keyWord, print, null);
        List<OralMedicineListDTO> oralList = new CopyOnWriteArrayList<>();
        Map<String, List<OralMedicineListDTO>> distintMap = new ConcurrentHashMap<>();
        orderExecs.stream().forEach(x -> {
            if (StringUtils.isEmpty(x.getTimeMode()) || x.getOrderClassType().equals("2")) {
                String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(DateUtil.dateToString(DateUtil.stringToDate(x.getPlanBeginDatetime()),"HHmmss")).toString();
                OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                BeanUtils.copyProperties(x, oralMedicineListDTO);
                oralMedicineListDTO.setOralCode(oralCode);
                List<OralMedicineListDTO> list = distintMap.get(oralCode);
                if (CollectionUtils.isEmpty(list)) {
                    list = new CopyOnWriteArrayList<>();
                }
                oralMedicineListDTO.setFreqData(DateUtil.dateToString(DateUtil.stringToDate(x.getPlanBeginDatetime()),"HH:mm:ss"));
                list.add(oralMedicineListDTO);
                distintMap.put(oralCode, list);

            } else if (x.getTimeMode().equals("0")) {
                Date beginDateTime = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd HH:mm:ss");
                Date beginDate = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd");
                //如果指定时间的0点小于开始时间，则使用开始时间计算
                Date startTime = executeDate;//如果走药品规则,就从开立时间往下走,如果不走规则,直接当天全部显示
                if ("QOD".equals(x.getFreq())) {
                    startTime = beginDate;
                }
                Date endTime = DateUtil.stringToDate(x.getPlanEndDatetime());
                CronDescriber cronDescriber = JSONObject.parseObject(x.getCronDescriber(), CronDescriber.class);
                String expression = CronUtil.createCronExpression(cronDescriber, startTime);
                CronExpression cronExpression = null;
                try {
                    cronExpression = new CronExpression(expression);
                } catch (ParseException e) {
                    return;
                }
                startTime = cronExpression.getNextValidTimeAfter(startTime);
                /*if (startTime.after(DateUtil.getDateAfter(DateUtil.stringToDate(date), 1))) {//执行时间与创建时间一致.非间隔时间表达式会不包含.会向前推一天,需要判断后手动回
                    startTime = DateUtil.getDateBefore(startTime, 1);
                }*/

                //while (startTime.before(executeEndDateTime) && (null == x.getPlanEndDatetime() || startTime.before(endTime)) && qodAddFlag) {
                if ("QOD".equals(x.getFreq())) {
                    while (startTime.before(executeEndDateTime) && (null == x.getPlanEndDatetime() || startTime.before(endTime))) {
                        if(!(!executeDate.before(startTime)) && ((executeDate.equals(beginDate) && (startTime.after(beginDateTime) || startTime.equals(beginDateTime))) || !executeDate.equals(beginDate))){
                            OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                            BeanUtils.copyProperties(x, oralMedicineListDTO);
                            String executeTimeStr = DateUtil.dateToString(startTime, "yyyy-MM-dd HH:mm:ss").substring(11);
                            String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(executeTimeStr.replaceAll(":", "")).toString();
                            oralMedicineListDTO.setOralCode(oralCode);
                            oralMedicineListDTO.setFreqData(executeTimeStr);
                            List<OralMedicineListDTO> list = distintMap.get(oralCode);
                            if (CollectionUtils.isEmpty(list)) {
                                list = new CopyOnWriteArrayList<>();
                            }
                            list.add(oralMedicineListDTO);
                            distintMap.put(oralCode, list);
                        }
                        startTime = cronExpression.getNextValidTimeAfter(startTime);
                    }
                }else{
                    while (startTime.before(executeEndDateTime) && (null == x.getPlanEndDatetime() || startTime.before(endTime))) {
                        if(!(!executeDate.before(startTime))){
                            if (!startTime.before(beginDateTime)) {
                                OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                                BeanUtils.copyProperties(x, oralMedicineListDTO);
                                String executeTimeStr = DateUtil.dateToString(startTime, "yyyy-MM-dd HH:mm:ss").substring(11);
                                String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(executeTimeStr.replaceAll(":", "")).toString();
                                oralMedicineListDTO.setOralCode(oralCode);
                                oralMedicineListDTO.setFreqData(executeTimeStr);
                                List<OralMedicineListDTO> list = distintMap.get(oralCode);
                                if (CollectionUtils.isEmpty(list)) {
                                    list = new CopyOnWriteArrayList<>();
                                }
                                list.add(oralMedicineListDTO);
                                distintMap.put(oralCode, list);
                            }
                        }
                        startTime = cronExpression.getNextValidTimeAfter(startTime);
                    }
                }
            } else {
                Date beginDateTime = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd HH:mm:ss");
                Date beginDate = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd");
                //如果指定时间的0点小于开始时间，则使用开始时间计算
                Date startTime = executeDate.equals(beginDate) ? beginDateTime : executeDate;
                Date endTime = DateUtil.stringToDate(x.getPlanEndDatetime());
                CronDescriber cronDescriber = JSONObject.parseObject(x.getCronDescriber(), CronDescriber.class);
                String expression = CronUtil.createCronExpression(cronDescriber, null);
                CronExpression cronExpression = null;
                try {
                    cronExpression = new CronExpression(expression);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (startTime.equals(beginDateTime) && x.getTimeMode().equals("1")) {
                    startTime = executeDate;
                }
                startTime = cronExpression.getNextValidTimeAfter(startTime);
                /*if (startTime.equals(DateUtil.getDateAfter(beginDateTime, 1)) || startTime.after(executeEndDateTime)) {//执行时间与创建时间一致.非间隔时间表达式会不包含.会向前推一天,需要判断后手动回
                    startTime = DateUtil.getDateBefore(startTime, 1);
                }*/
                while (startTime.before(executeEndDateTime) && (null == x.getPlanEndDatetime() || startTime.before(endTime)) && (startTime.after(beginDateTime) || startTime.equals(beginDateTime))) {
                    OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                    BeanUtils.copyProperties(x, oralMedicineListDTO);
                    String executeTimeStr = DateUtil.dateToString(startTime, "yyyy-MM-dd HH:mm:ss").substring(11);
                    String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(executeTimeStr.replaceAll(":", "")).toString();
                    oralMedicineListDTO.setOralCode(oralCode);
                    oralMedicineListDTO.setFreqData(executeTimeStr);
                    List<OralMedicineListDTO> list = distintMap.get(oralCode);
                    if (CollectionUtils.isEmpty(list)) {
                        list = new CopyOnWriteArrayList<>();
                    }
                    list.add(oralMedicineListDTO);
                    distintMap.put(oralCode, list);
                    startTime = DateUtil.increasedSeconds(startTime, Integer.parseInt(x.getExeCycleStamp()));
                }
            }
        });


        distintMap.keySet().stream().forEach(x -> {
            String freqStr = x.substring(x.length() - 6);
            String filterStr = freq.replaceAll(":", "");
            if (freqStr.equals(filterStr) || freq.equals("-1")) {
                List<OralMedicineListDTO> list = distintMap.get(x);
                OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                if (CollectionUtils.isNotEmpty(list)) {
                    oralMedicineListDTO.setInpatNum(list.get(0).getInpatNum());
                    oralMedicineListDTO.setPatName(list.get(0).getPatName());
                    oralMedicineListDTO.setSex(list.get(0).getSex());
                    oralMedicineListDTO.setBedNo(list.get(0).getBedNo());
                    oralMedicineListDTO.setOrderNo(list.get(0).getOrderNo());
                    oralMedicineListDTO.setMedicalNum(list.get(0).getMedicalNum());
                    oralMedicineListDTO.setFreqData(list.get(0).getFreqData());
                    oralMedicineListDTO.setOralCode(list.get(0).getOralCode());
                    oralMedicineListDTO.setDrugList(list);
                    oralList.add(oralMedicineListDTO);
                }
            }
        });
        if (freq != null && !freq.equals("-1")) {
            oralList.forEach(item -> {
                if (!item.getFreqData().equals(freq)) {
                    oralList.remove(item);
                }
            });
        }
        return ResultGenerator.genOkResult(oralList);
    }

    List<Map<String, Object>> getRelationList(String freq, String date, String keyWord, String nodeName, String turnBackFlag, String inpatNum, String nName, String status) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
        String formatDate = "";
        try {
            if (StringUtils.isNotBlank(date)) {
                formatDate = sdf.format(sdf3.parse(date));
            }
        } catch (Exception e) {
            log.error("时间解析错误");
        }
        SimpleDateFormat hSdf = new SimpleDateFormat("HH");
        String hour = hSdf.format(new Date(new Date().getTime() + (1000 * 60 * 60)));
        hour += ":00:00";

        List<Map<String, String>> orderList = oralMedicineMapper.getRelationList(formatDate, freq, null, keyWord, null, nodeName, turnBackFlag, inpatNum);

        List<Map<String, Object>> result = new ArrayList();
        Map<String, List<Map<String, String>>> orderListGroup = orderList.stream().collect(Collectors.groupingBy(d -> d.get("qrCode")));
        for (String key : orderListGroup.keySet()) {
            Map<String, Object> inpatres = new HashMap<>();//一条数据
            List<Map<String, String>> orders = new ArrayList<>();//药品集合
            String exTime = DateUtil.dateToString(DateUtil.stringToDate(key.
                    substring(key.length() - 12, key.length()), "yyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss");

            for (Map<String, String> order : orderList) {
                if (key.equals(order.get("qrCode"))) {
                    if (StringUtils.isNotBlank(order.get("bedNo"))) {
                        inpatres.put("bedNo", order.get("bedNo"));
                    } else {
                        inpatres.put("bedNo", "0");
                    }
                    inpatres.put("nodeName", nName);
                    inpatres.put("status", status);
                    inpatres.put("inpatNum", order.get("inpatNum"));
                    inpatres.put("inpatNo", order.get("inpatNum").split("-")[0]);
                    inpatres.put("administration", order.get("administration"));
                    inpatres.put("patName", order.get("patName"));
                    inpatres.put("remark", order.get("remark"));
                    inpatres.put("sex", order.get("sex"));
                    inpatres.put("oralCode", order.get("qrCode"));
                    inpatres.put("qrCode", order.get("qrCode"));
                    inpatres.put("freqData", order.get("freqData"));
                    inpatres.put("dosageBasicUnit", order.get("dosageBasicUnit"));

                    order.put("itemDosage", order.get("itemDosage") + order.get("unit"));
                    Map<String, String> orderres = new HashMap<>();//一条药品数据,归类于一条病人数据的集合中
                    orderres.putAll(order);
                    orders.add(orderres);
                }
            }
            Map<String, String> turnBack = oralMedicineMapper.getTurnBackByQrcode(inpatres.get("qrCode").toString());
            if (turnBack != null) {
                inpatres.put("returnRemark", turnBack.get("RETURN_REASON"));
                inpatres.put("returnPerason", turnBack.get("RETURN_PERSON_NAME"));
                inpatres.put("returnTime", turnBack.get("returnTime"));
            }
            inpatres.put("executionTime", exTime);
            inpatres.put("drugList", orders);
            if (orders != null && orders.size() > 0) {
                String taskQrCode = orders.get(0).get("taskQrCode");
                if (StringUtils.isNotBlank(taskQrCode)) {
                    List<Map<String, Object>> infusionExecutionList = taskExecuteMapper.queryTaskExecuteBatchByQrCode(taskQrCode, null);
                    infusionExecutionList = infusionExecutionList.stream().filter(infusion -> "1".equals(infusion.get("status").toString())).collect(Collectors.toList());
                    inpatres.put("infusionExecutionList", infusionExecutionList);
                }
                inpatres.put("inpatorderdataIds", StringUtils.join(orders.stream().map(s -> s.get("inpatorderdataId")).collect(Collectors.toList()), ","));
                result.add(inpatres);
            }

        }
        int total = result.size();
        result.sort((a, b) -> Integer.parseInt(a.get("bedNo").toString() + new BigDecimal(a.get("executionTime").toString().substring(8, 16).replaceAll("-", "").replaceAll(" ", "").replaceAll(":", ""))) -
                Integer.parseInt(b.get("bedNo").toString() + new BigDecimal(b.get("executionTime").toString().substring(8, 16).replaceAll("-", "").replaceAll(" ", "").replaceAll(":", ""))));
        /*if(page!=0 &&pageSzie!=0){
            result = result.stream().skip((page-1)* pageSzie).limit(pageSzie).collect(Collectors.toList());
        }

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(result);
        pageInfo.setTotal(total);*/
        return result;
    }

    public List<Map<String, Object>> getReturnList(String inpatNum, String date, String keyWord, String nodeName, String status) {
        List<Map<String, String>> drugList = oralMedicineMapper.getReturnListByInpatNum(null, inpatNum, date, keyWord, "termination");
        Map<String, List<Map<String, String>>> bookMap = drugList.stream().collect(Collectors.groupingBy(b -> b.get("qrCode")));
        List<Map<String, Object>> resultList = new ArrayList();
        for (String key : bookMap.keySet()) {
            List<Map<String, String>> drugItem = bookMap.get(key);
            Map<String, Object> inpatres = new HashMap<>();
            List<Map<String, String>> orders = new ArrayList<>();
            for (Map<String, String> order : drugItem) {
                if (StringUtils.isNotBlank(order.get("bedNo"))) {
                    inpatres.put("bedNo", order.get("bedNo"));
                } else {
                    inpatres.put("bedNo", "0");
                }
                inpatres.put("nodeName", nodeName);
                inpatres.put("status", status);
                inpatres.put("inpatNum", order.get("inpatNum"));
                inpatres.put("inpatNo", order.get("inpatNum").split("-")[0]);
                inpatres.put("administration", order.get("freq"));
                inpatres.put("patName", order.get("patName"));
                inpatres.put("remark", order.get("remark"));
                inpatres.put("sex", order.get("sex"));
                inpatres.put("oralCode", order.get("qrCode"));
                inpatres.put("qrCode", order.get("qrCode"));
                inpatres.put("returnRemark", order.get("returnRemark"));
                inpatres.put("returnPerason", order.get("returnPerason"));
                inpatres.put("returnTime", order.get("returnTime"));
                if (order.get("executionTime") != null && order.get("executionTime").length() == 12) {
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyMMddHHmmss");
                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    try {
                        inpatres.put("executionTime", sdf2.format(sdf1.parse(order.get("executionTime"))));
                    } catch (Exception e) {
                        log.error("时间解析错误" + e);
                    }
                } else {
                    inpatres.put("executionTime", "");
                }
                order.put("itemDosage", order.get("itemDosage") + order.get("unit"));
                Map<String, String> orderres = new HashMap<>();//一条药品数据,归类于一条病人数据的集合中
                orderres.putAll(order);
                orders.add(orderres);
            }
            inpatres.put("drugList", orders);
            if (orders.size() > 0) {
                String tQrCode = null;
                for (Map<String, String> drugMap : orders) {
                    String taskQrCode = taskExecuteMapper.queryOralOrdersRelationByQrCodeAndInpatorderdataId(drugMap.get("qrCode"), drugMap.get("inpatorderdataId"));
                    if (StringUtils.isBlank(tQrCode) && StringUtils.isNotBlank(taskQrCode)) {
                        tQrCode = taskQrCode;
                    }
                }
                if (StringUtils.isNotBlank(tQrCode)) {
                    List<Map<String, Object>> infusionExecutionList = taskExecuteMapper.queryTaskExecuteBatchByQrCode(tQrCode, null);
                    infusionExecutionList = infusionExecutionList.stream().filter(infusion -> "1".equals(infusion.get("status").toString()) && "1".equals(infusion.get("showFlag").toString()) && "0".equals(infusion.get("stopFlag").toString())).collect(Collectors.toList());

                    inpatres.put("infusionExecutionList", infusionExecutionList);
                } else {
                    List<Map<String, Object>> infusionExecutionList = new CopyOnWriteArrayList<>();
                    Map<String, Object> infusionExecutionMap = new ConcurrentHashMap<>();
                    infusionExecutionMap.put("nodeName", "口服药终止");
                    infusionExecutionMap.put("executeDatetime", inpatres.get("returnTime"));
                    infusionExecutionMap.put("userName", inpatres.get("returnPerason"));
                    infusionExecutionMap.put("showFlag", "1");
                    infusionExecutionMap.put("stopFlag", "0");
                    infusionExecutionList.add(infusionExecutionMap);
                    inpatres.put("infusionExecutionList", infusionExecutionList);
                }

                resultList.add(inpatres);
            }
        }
        resultList.sort((a, b) -> Integer.parseInt(a.get("bedNo").toString() + a.get("executionTime").toString().substring(8, 16).replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "")) -
                Integer.parseInt(b.get("bedNo").toString() + b.get("executionTime").toString().substring(8, 16).replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "")));
        /*int total = resultList.size();
        if(resultList.size()>0){
            resultList.stream().skip((page-1+1)* pageSzie).limit(pageSzie).collect(Collectors.toList());
        }
        PageInfo pageInfo = new PageInfo(resultList);
        pageInfo.setTotal(total);*/
        return resultList;
    }

    public List<Map<String, Object>> getInfusionList(String inpatNum, String dateTime, String keyWord, String administration, String nodeName, String flag) {
        List<String> staticWardList = taskExecuteMapper.queryStaticAllocationWard(VarCodeEnum.SYLCZX.getVarCode());
        String beginTime = dateTime + " 00:00";
        String endTime = dateTime + " 23:59";
        List<Map<String, Object>> list = new ArrayList<>();

        List<Map<String, String>> qrCodeList = new ArrayList<>();
        //创建频次任务
        list = taskExecuteMapper.orderQRCodeNew(inpatNum, beginTime, endTime, administration, flag,staticWardList);
        String finalBeginTime = beginTime;
        String finalEndTime = endTime;
        // 添加条码类型
        String codeType = this.taskExecuteMapper.getAdministrationName(administration);

        List<Map<String, Object>> resultList = new ArrayList<>();
        list.stream().forEach(map -> {
            //computeAge(map);
            List<Map<String, Object>> orderList = taskExecuteMapper.queryOrdersByInpatNum(map.get("inpatNum").toString(), map.get("orderNo").toString());
            map.put("drugList", orderList);
            map.put("codeType", codeType);
            Map<String, Object> mainOrder = orderList.get(0);
            try {
                if ("1".equals(flag)) {
                    createFreQrCode(mainOrder, map, finalBeginTime, finalEndTime, dateTime);
                } else if ("2".equals(flag)) {
                    createIntravenousFreQrCode(mainOrder, map, finalBeginTime, finalEndTime, dateTime);
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }
            List<Map<String, String>> qrCodesList = (List<Map<String, String>>) map.get("qrCodeList");
            if (CollectionUtils.isNotEmpty(qrCodesList)) {
                for (Map<String, String> qrCodesMap : qrCodesList) {
                    Map<String, Object> stopMap = new ConcurrentHashMap<>();
                    stopMap.put("executionTime", qrCodesMap.get("execDate"));
                    stopMap.put("oralCode", qrCodesMap.get("qrCode"));
                    stopMap.put("qrCode", qrCodesMap.get("qrCode"));
                    stopMap.put("patName", map.get("patName"));
                    stopMap.put("drugList", map.get("drugList"));
                    stopMap.put("inpatNum", map.get("inpatNum"));
                    stopMap.put("bedNo", map.get("bedNo"));
                    stopMap.put("inpatNo", map.get("medicalNum"));
                    stopMap.put("sex", map.get("sex"));
                    stopMap.put("administration", map.get("administration")==null?"":map.get("administration"));
                    stopMap.put("status", "0");
                    List<Map<String, Object>> orderSubNoList = orderList.stream().filter(s -> "1".equals(s.get("orderSubNo").toString())).collect(Collectors.toList());
                    stopMap.put("inpatorderdataIds", StringUtils.join(orderSubNoList.stream().map(s -> s.get("inpatorderdataId")).collect(Collectors.toList()), ","));
                    stopMap.put("nodeName", nodeName);
                    List<Map<String, Object>> infusionExecutionList = taskExecuteMapper.queryTaskExecuteBatchByQrCode(qrCodesMap.get("qrCode"), null);
                    if (CollectionUtils.isNotEmpty(infusionExecutionList)) {
                        List<Map<String, Object>> infusionExecutionMap = infusionExecutionList.stream().filter(s -> "0".equals(s.get("status"))).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(infusionExecutionMap)) {
                            String cstatus = setStatus(nodeName, qrCodesMap.get("qrCode"), infusionExecutionList, (String) stopMap.get("administration"), (List<Map<String, Object>>) map.get("drugList"));
                            infusionExecutionList = infusionExecutionList.stream().filter(infusion -> "1".equals(infusion.get("status").toString())).collect(Collectors.toList());
                            //1 执行中
                            stopMap.put("status", cstatus);
                        } else {
                            infusionExecutionList = infusionExecutionList.stream().filter(infusion -> "1".equals(infusion.get("status").toString())).collect(Collectors.toList());
                            // 2 已执行
                            stopMap.put("status", "2");
                            //判断该任务是否终止
                            List<AtomizeMedReturnEntity> atomizeList = taskExecuteMapper.queryAtomizeMedReturnByQrCode(qrCodesMap.get("qrCode"));
                            if (CollectionUtils.isNotEmpty(atomizeList)) {
                                terminationMethod(atomizeList, infusionExecutionList, nodeName, stopMap);
                            }
                        }
                        //在进行数据过滤
                        infusionExecutionList = infusionExecutionList.stream().filter(infusion -> "1".equals(infusion.get("showFlag").toString()) && "0".equals(infusion.get("stopFlag").toString())).collect(Collectors.toList());
                        stopMap.put("infusionExecutionList", infusionExecutionList);
                    } else {
                        //判断该任务是否终止
                        List<AtomizeMedReturnEntity> atomizeList = taskExecuteMapper.queryAtomizeMedReturnByQrCode(qrCodesMap.get("qrCode"));
                        if (CollectionUtils.isNotEmpty(atomizeList)) {
                            infusionExecutionList = new CopyOnWriteArrayList<>();
                            terminationMethod(atomizeList, infusionExecutionList, nodeName, stopMap);
                        } else {
                            //0 未执行
                            stopMap.put("status", "0");
                            stopMap.put("infusionExecutionList", infusionExecutionList);
                        }
                    }
                    resultList.add(stopMap);
                }
            }
        });
        return resultList;
    }


    public String setStatus(String nodeName,String qrCode,List<Map<String, Object>> infusionExecutionList,String administration,List<Map<String, Object>> drugList){
        String status="0";
        Map<String, String> map = new CopyOnWriteMap<>();
        if("输液".equals(nodeName)){
            map = orderMapper.selectInfusionTime(null,qrCode);

        }else if("雾化".equals(nodeName)){
            map = orderMapper.selectAtomizationTime(null,qrCode);

        }else if("肠内营养".equals(nodeName)){
            map = orderMapper.selectNutritionTime(null,qrCode);

        }else if("注射".equals(nodeName)){
            if("皮内注射".equals(administration) || "皮试".equals(administration)){
                map = orderMapper.selectInjectionTime1(null,qrCode);
            }else if("皮下注射".equals(administration) || "皮下注射(胰岛素)".equals(administration)|| "M".equals(administration)){
                map = orderMapper.selectInjectionTime2(null,qrCode);
            }else if("V".equals(administration) || "注射用".equals(administration)|| "V微量泵维持".equals(administration) || "V(50ML)".equals(administration)){
                map = orderMapper.selectInfusionTime(null,qrCode);
            }else {
                String orderItem=null;
                if(CollectionUtils.isNotEmpty(drugList)){
                    orderItem = (String)drugList.get(0).get("ordersItem");
                }
                if(StringUtils.isNotBlank(orderItem) && ("碘试验(病房)".equals(orderItem) || "碘试验(注射室)".equals(orderItem))){
                    map = orderMapper.selectInjectionTime3(null,qrCode);
                }else if(StringUtils.isNotBlank(orderItem) &&  "胰岛素泵持续皮下注射胰岛素".equals(orderItem)){
                    map = orderMapper.selectInjectionTime4(null,qrCode);
                }
            }
        }

        if(map!=null && StringUtils.isNotBlank(map.get("taskBatchId"))) {
            Map<String, String> finalMap = map;
            List<Map<String, Object>> collect = infusionExecutionList.stream().filter(x -> finalMap.get("taskBatchId").equals(x.get("taskBatchId"))).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(collect)){
                status="1";
            }
        }
        return status;
    }

    public void terminationMethod(List<AtomizeMedReturnEntity> atomizeList, List<Map<String, Object>> infusionExecutionList, String nodeName, Map<String, Object> stopMap) {
        //判断该任务是否终止
        Map<String, Object> infusionExecutionMap = new HashMap<>();
        infusionExecutionMap.put("nodeName", nodeName + "终止");
        if (atomizeList.get(0).getReturnTime() != null) {
            infusionExecutionMap.put("executeDatetime", DateUtil.dateToString(new Date(atomizeList.get(0).getReturnTime().getTime()), "yyyy-MM-dd HH:mm"));
        }
        infusionExecutionMap.put("userName", atomizeList.get(0).getReturnUserId() == null ? "" : atomizeList.get(0).getReturnUserId());
        infusionExecutionMap.put("showFlag", "1");
        infusionExecutionMap.put("stopFlag", "0");
        infusionExecutionList.add(infusionExecutionMap);
        // 2:已执行
        stopMap.put("status", "2");
        stopMap.put("infusionExecutionList", infusionExecutionList);
    }

    public List<Map<String, Object>> getAtomizationList(String inpatNum, String dateTime, String keyWord, List<String> administrations, String nodeName, String status) {
        String beginTime = dateTime + " 00:00";
        String endTime = dateTime + " 23:59";
        List<Map<String, Object>> list = new ArrayList<>();

        List<Map<String, String>> qrCodeList = new ArrayList<>();
        //创建频次任务
        list = taskExecuteMapper.orderQRCodeNews(inpatNum, beginTime, endTime, administrations);
        String finalBeginTime = beginTime;
        String finalEndTime = endTime;
        // 添加条码类型
        String codeType = this.taskExecuteMapper.getAdministrationName(administrations.get(0));

        List<Map<String, Object>> resultList = new ArrayList<>();
        list.stream().forEach(map -> {
            //computeAge(map);
            List<Map<String, Object>> orderList = taskExecuteMapper.queryOrdersByInpatNum(map.get("inpatNum").toString(), map.get("orderNo").toString());
            map.put("drugList", orderList);
            map.put("codeType", codeType);
            Map<String, Object> mainOrder = orderList.get(0);
            try {
                createFreQrCode(mainOrder, map, finalBeginTime, finalEndTime, dateTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            List<Map<String, String>> qrCodesList = (List<Map<String, String>>) map.get("qrCodeList");
            if (CollectionUtils.isNotEmpty(qrCodesList)) {
                for (Map<String, String> qrCodesMap : qrCodesList) {
                    Map<String, Object> stopMap = new ConcurrentHashMap<>();
                    stopMap.put("executionTime", qrCodesMap.get("execDate"));
                    stopMap.put("oralCode", qrCodesMap.get("qrCode"));
                    stopMap.put("qrCode", qrCodesMap.get("qrCode"));
                    stopMap.put("patName", map.get("patName"));
                    stopMap.put("drugList", map.get("drugList"));
                    stopMap.put("patName", map.get("patName"));
                    stopMap.put("inpatNum", map.get("inpatNum"));
                    stopMap.put("bedNo", map.get("bedNo"));
                    stopMap.put("inpatNo", map.get("medicalNum"));
                    stopMap.put("administration", map.get("administration")==null?"":map.get("administration"));
                    stopMap.put("sex", map.get("sex"));
                    stopMap.put("nodeName", nodeName);
                    stopMap.put("status", "0");
                    List<Map<String, Object>> orderSubNoList = orderList.stream().filter(s -> "1".equals(s.get("orderSubNo").toString())).collect(Collectors.toList());
                    stopMap.put("inpatorderdataIds", StringUtils.join(orderSubNoList.stream().map(s -> s.get("inpatorderdataId")).collect(Collectors.toList()), ","));
                    List<Map<String, Object>> infusionExecutionList = taskExecuteMapper.queryTaskExecuteBatchByQrCode(qrCodesMap.get("qrCode"), null);
                    if (CollectionUtils.isNotEmpty(infusionExecutionList)) {
                        List<Map<String, Object>> infusionExecutionMap = infusionExecutionList.stream().filter(s -> "0".equals(s.get("status"))).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(infusionExecutionMap)) {
                            String cstatus = setStatus(nodeName,qrCodesMap.get("qrCode"),infusionExecutionList,(String)stopMap.get("administration"),(List<Map<String, Object>>)map.get("drugList"));
                            infusionExecutionList = infusionExecutionList.stream().filter(infusion -> "1".equals(infusion.get("status").toString())).collect(Collectors.toList());
                            //1 执行中
                            stopMap.put("status", cstatus);
                        } else {
                            infusionExecutionList = infusionExecutionList.stream().filter(infusion -> "1".equals(infusion.get("status").toString())).collect(Collectors.toList());
                            //2 已执行
                            stopMap.put("status", "2");
                            //判断该任务是否终止
                            if (!"雾化".equals(nodeName)) {
                                Map<String, Object> lastTaskMap = infusionExecutionList.stream().skip(infusionExecutionList.size() - 1).findFirst().orElse(null);
                                if (lastTaskMap != null) {
                                    String varCode = (String) lastTaskMap.get("varCode");
                                    String stopFlag = (String) lastTaskMap.get("stopFlag");
                                    if (StringUtils.isNotBlank(varCode) && (VarCodeEnum.RWJD_SYZX.getVarCode().equalsIgnoreCase(varCode)
                                            || VarCodeEnum.RWJD_BFBYHD.getVarCode().equalsIgnoreCase(varCode)
                                            || VarCodeEnum.RWJD_BFJYHD.getVarCode().equalsIgnoreCase(varCode)
                                            || VarCodeEnum.PXZS_JRZS.getVarCode().equalsIgnoreCase(varCode)
                                            || VarCodeEnum.CNYYGZ.getVarCode().equalsIgnoreCase(varCode)
                                            || VarCodeEnum.CZ_YDSZS.getVarCode().equalsIgnoreCase(varCode)
                                            || VarCodeEnum.RWJD_SYXS.getVarCode().equalsIgnoreCase(varCode)
                                            || (VarCodeEnum.DSYJG.getVarCode().equalsIgnoreCase(varCode) && "1".equals(stopFlag))
                                    )) {
                                        List<AtomizeMedReturnEntity> atomizeList = taskExecuteMapper.queryAtomizeMedReturnByQrCode(qrCodesMap.get("qrCode"));
                                        if (CollectionUtils.isNotEmpty(atomizeList)) {
                                            terminationMethod(atomizeList, infusionExecutionList, nodeName, stopMap);
                                        }
                                    }
                                }
                            }
                        }
                        //在进行数据过滤
                        //infusionExecutionList = infusionExecutionList.stream().filter(infusion -> "1".equals(infusion.get("showFlag").toString())).collect(Collectors.toList());
                        infusionExecutionList = infusionExecutionList.stream().filter(infusion -> "1".equals(infusion.get("showFlag").toString()) && "0".equals(infusion.get("stopFlag").toString())).collect(Collectors.toList());
                        stopMap.put("infusionExecutionList", infusionExecutionList);
                    } else {
                        //判断该任务是否终止
                        List<AtomizeMedReturnEntity> atomizeList = taskExecuteMapper.queryAtomizeMedReturnByQrCode(qrCodesMap.get("qrCode"));
                        if (CollectionUtils.isNotEmpty(atomizeList)) {
                            infusionExecutionList = new CopyOnWriteArrayList<>();
                            terminationMethod(atomizeList, infusionExecutionList, nodeName, stopMap);
                        } else {
                            //0 未执行
                            stopMap.put("status", "0");
                            stopMap.put("infusionExecutionList", infusionExecutionList);
                        }
                    }
                    resultList.add(stopMap);
                }
            }
        });
        return resultList;
    }

    public void createFreQrCode(Map<String, Object> mainOrder111, Map<String, Object> result, String beginTime1, String endTime1, String date) throws ParseException {
        String executeDateStr = date.replaceAll("-", "");
        Date executeDate = DateUtil.stringToDate(executeDateStr, "yyyyMMdd");
        Date executeEndDateTime = DateUtil.getDateAfter(DateUtil.stringToDate(executeDateStr, "yyyyMMdd"), 1);
        List<Map<String, String>> qrCodeList = new ArrayList<>();
        String freq = result.get("freq") == null ? "" : result.get("freq").toString();
        String freqData = result.get("freqData") == null ? "" : result.get("freqData").toString();
        //  临时医嘱
        if (org.apache.commons.lang.StringUtils.isEmpty((String) result.get("TIMEMODE")) || result.get("orderType").equals("2")) {
            Date beginDateTime = DateUtil.stringToDate(result.get("planBeginDatetime").toString(), "yyyy-MM-dd HH:mm:ss");
            String begindateTimeFormat1 = DateUtil.dateToString(beginDateTime, "yyyyMMddHHmmss");
            String begindateTimeFormat2 = DateUtil.dateToString(beginDateTime, "yyyy-MM-dd HH:mm:ss");
            String oralCode = new StringBuffer("y_").append(result.get("medicalNum")).append(begindateTimeFormat1).append("_").append(result.get("orderNo")).toString();
            Map<String, String> map = new HashMap<String, String>();
            map.put("qrCode", oralCode);
            map.put("execDate", begindateTimeFormat2);
            qrCodeList.add(map);

        } else if (result.get("TIMEMODE").equals("0")) {
            Date beginDateTime = DateUtil.stringToDate(result.get("planBeginDatetime").toString(), "yyyy-MM-dd HH:mm:ss");
            Date beginDate = DateUtil.stringToDate(result.get("planBeginDatetime").toString(), "yyyy-MM-dd");
            //如果指定时间的0点小于开始时间，则使用开始时间计算
            Date startTime = executeDate;
            if ("QOD".equals(result.get("freq"))) {
                startTime = beginDate;
            }
            Date eTime = null;
            if (result.get("planEndDatetime") != null) {
                eTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) result.get("planEndDatetime"));
            }
            Date endTime = result.get("planEndDatetime") == null ? executeEndDateTime : (eTime.compareTo(executeEndDateTime) >= 0 ? executeEndDateTime : eTime);
            //Date endTime = DateUtil.stringToDate((String)result.get("planEndDatetime"));
            CronDescriber cronDescriber = JSONObject.parseObject((String) result.get("CRON_DESCRIBER"), CronDescriber.class);
            String expression = CronUtil.createCronExpression(cronDescriber, startTime);
            CronExpression cronExpression = null;
            try {
                cronExpression = new CronExpression(expression);
            } catch (ParseException e) {
                e.printStackTrace();
                return;
            }
            startTime = cronExpression.getNextValidTimeAfter(startTime);
            /*if (startTime.equals(DateUtil.getDateAfter(beginDateTime, 1)) || startTime.after(executeEndDateTime)) {//执行时间与创建时间一致.非间隔时间表达式会不包含.会向前推一天,需要判断后手动回
                startTime = DateUtil.getDateBefore(startTime, 1);
            }*/
            boolean qodAddFlag=true;

            //String specialUsageFlag = taskExecuteMapper.querySpecialUsage(result.get("administrationId").toString());
            //while (startTime.before(executeEndDateTime) && (null == result.get("planEndDatetime") || startTime.before(endTime)) && specialFlag) {
            while (startTime.before(executeEndDateTime) && (null == result.get("planEndDatetime") || startTime.before(endTime)) && qodAddFlag) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("execDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime));

                String oralCode = new StringBuffer("y_").append(result.get("medicalNum")).append(new SimpleDateFormat("yyyyMMddHHmmss").format(startTime)).append("_").append(result.get("orderNo")).toString();
                String specialUsageFlag = result.get("administrationId") == null ? null : taskExecuteMapper.querySpecialUsage(result.get("administrationId").toString());
                boolean specialFlag = true;
                if ((org.apache.commons.lang3.StringUtils.isNotBlank(specialUsageFlag) && startTime.before(beginDateTime)) || (result.get("administrationId") == null && startTime.before(beginDateTime))) {
                    specialFlag = false;
                    if("注射用".equals(result.get("administration"))){
                        specialFlag = true;
                    }
                }

                if(!executeDate.before(startTime)){
                    specialFlag = false;
                }

                if(!("输液单".equals(result.get("codeType")) || "注射用".equals(result.get("administration")))){
                    if(!(!(!executeDate.before(startTime)) && ((executeDate.equals(beginDate) && (startTime.after(beginDateTime) || startTime.equals(beginDateTime))) || !executeDate.equals(beginDate)))){
                        specialFlag = false;
                    }
                }

                if (specialFlag) {
                    map.put("qrCode", oralCode);
                    qrCodeList.add(map);
                }
                startTime = cronExpression.getNextValidTimeAfter(startTime);

            }
        } else {
            Date beginDateTime = DateUtil.stringToDate(result.get("planBeginDatetime").toString(), "yyyy-MM-dd HH:mm:ss");
            Date beginDate = DateUtil.stringToDate(result.get("planBeginDatetime").toString(), "yyyy-MM-dd");
            //如果指定时间的0点小于开始时间，则使用开始时间计算
            Date startTime = executeDate.equals(beginDate) ? beginDateTime : DateUtil.getDateAfterRedSecond(executeDate, 1);
            //Date endTime = DateUtil.stringToDate(result.get("planEndDatetime").toString());
            Date eTime = null;
            if (result.get("planEndDatetime") != null) {
                eTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) result.get("planEndDatetime"));
            }
            Date endTime = result.get("planEndDatetime") == null ? executeEndDateTime : (eTime.compareTo(executeEndDateTime) >= 0 ? executeEndDateTime : eTime);
            CronDescriber cronDescriber = JSONObject.parseObject((String) result.get("CRON_DESCRIBER"), CronDescriber.class);
            String expression = CronUtil.createCronExpression(cronDescriber, null);
            CronExpression cronExpression = null;
            try {
                cronExpression = new CronExpression(expression);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (startTime.equals(beginDateTime) && result.get("TIMEMODE").equals("1")) {
                startTime = executeDate;
            }
            startTime = cronExpression.getNextValidTimeAfter(startTime);
            /*if (startTime.equals(DateUtil.getDateAfter(beginDateTime, 1)) || startTime.after(executeEndDateTime)) {//执行时间与创建时间一致.非间隔时间表达式会不包含.会向前推一天,需要判断后手动回
                startTime = DateUtil.getDateBefore(startTime, 1);
            }*/
            while (startTime.before(executeEndDateTime) && (null == result.get("planEndDatetime") || startTime.before(endTime))) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("execDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime));


                String oralCode = new StringBuffer("y_").append(result.get("medicalNum")).append(new SimpleDateFormat("yyyyMMddHHmmss").format(startTime)).append("_").append(result.get("orderNo")).toString();
                boolean specialFlag = true;
                String specialUsageFlag = result.get("administrationId") == null ? null : taskExecuteMapper.querySpecialUsage(result.get("administrationId").toString());
                //if (org.apache.commons.lang3.StringUtils.isNotBlank(specialUsageFlag) && startTime.before(beginDateTime)) {
                if ((org.apache.commons.lang3.StringUtils.isNotBlank(specialUsageFlag) && startTime.before(beginDateTime))
                        || (result.get("administrationId") == null && startTime.before(beginDateTime))) {
                    specialFlag = false;
                }
                if (specialFlag) {
                    map.put("qrCode", oralCode);
                    qrCodeList.add(map);
                }
                startTime = DateUtil.increasedSeconds(startTime, Integer.parseInt((String) result.get("exeCycleStamp")));

            }
        }
        result.put("qrCodeList", qrCodeList);
    }

    private void createIntravenousFreQrCode(Map<String, Object> mainOrder111, Map<String, Object> result, String beginTime1, String endTime1, String date) throws ParseException {
        String executeDateStr = date.replaceAll("-", "");
        Date executeDate = DateUtil.stringToDate(executeDateStr, "yyyyMMdd");
        Date executeEndDateTime = DateUtil.getDateAfter(DateUtil.stringToDate(executeDateStr, "yyyyMMdd"), 1);
        List<Map<String, String>> qrCodeList = new ArrayList<>();
        String freq = result.get("freq") == null ? "" : result.get("freq").toString();
        String freqData = result.get("freqData") == null ? "" : result.get("freqData").toString();
        //  临时医嘱
        if (org.apache.commons.lang.StringUtils.isEmpty((String) result.get("TIMEMODE")) || result.get("orderType").equals("2")) {
            Date beginDateTime = DateUtil.stringToDate(result.get("planBeginDatetime").toString(), "yyyy-MM-dd HH:mm:ss");
            String begindateTimeFormat1 = DateUtil.dateToString(beginDateTime, "yyyyMMddHHmmss");
            String begindateTimeFormat2 = DateUtil.dateToString(beginDateTime, "yyyy-MM-dd HH:mm:ss");
            String oralCode = new StringBuffer("j_").append(result.get("medicalNum")).append(begindateTimeFormat1.substring(2)).append(result.get("orderNo")).toString();
            Map<String, String> map = new HashMap<String, String>();
            map.put("qrCode", oralCode);
            map.put("execDate", begindateTimeFormat2);
            qrCodeList.add(map);

        } else if (result.get("TIMEMODE").equals("0")) {
            Date beginDateTime = DateUtil.stringToDate(result.get("planBeginDatetime").toString(), "yyyy-MM-dd HH:mm:ss");
            Date beginDate = DateUtil.stringToDate(result.get("planBeginDatetime").toString(), "yyyy-MM-dd");
            //如果指定时间的0点小于开始时间，则使用开始时间计算
            Date startTime = executeDate;
            if ("QOD".equals(result.get("freq"))) {
                startTime = beginDate;
            }
            Date eTime = null;
            if (result.get("planEndDatetime") != null) {
                eTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) result.get("planEndDatetime"));
            }
            Date endTime = result.get("planEndDatetime") == null ? executeEndDateTime : (eTime.compareTo(executeEndDateTime) >= 0 ? executeEndDateTime : eTime);
            //Date endTime = DateUtil.stringToDate((String)result.get("planEndDatetime"));
            CronDescriber cronDescriber = JSONObject.parseObject((String) result.get("CRON_DESCRIBER"), CronDescriber.class);
            String expression = CronUtil.createCronExpression(cronDescriber, startTime);
            CronExpression cronExpression = null;
            try {
                cronExpression = new CronExpression(expression);
            } catch (ParseException e) {
                e.printStackTrace();
                return;
            }
            startTime = cronExpression.getNextValidTimeAfter(startTime);

            boolean qodAddFlag=true;

            while (startTime.before(executeEndDateTime) && (null == result.get("planEndDatetime") || startTime.before(endTime)) && qodAddFlag) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("execDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime));

                String oralCode = new StringBuffer("j_").append(result.get("medicalNum")).append((new SimpleDateFormat("yyyyMMddHHmmss").format(startTime)).substring(2)).append(result.get("orderNo")).toString();
                String specialUsageFlag = result.get("administrationId") == null ? null : taskExecuteMapper.querySpecialUsage(result.get("administrationId").toString());
                boolean specialFlag = true;
                if (org.apache.commons.lang3.StringUtils.isNotBlank(specialUsageFlag) && startTime.before(beginDateTime)) {
                    specialFlag = false;
                }
                if(!executeDate.before(startTime)){
                    specialFlag = false;
                }
                if(!("输液单".equals(result.get("codeType")) || "注射用".equals(result.get("administration")))){
                    if(!(!(!executeDate.before(startTime)) && ((executeDate.equals(beginDate) && (startTime.after(beginDateTime) || startTime.equals(beginDateTime))) || !executeDate.equals(beginDate)))){
                        specialFlag = false;
                    }
                }
                if (specialFlag) {
                    map.put("qrCode", oralCode);
                    qrCodeList.add(map);
                }
                startTime = cronExpression.getNextValidTimeAfter(startTime);

            }
        } else {
            Date beginDateTime = DateUtil.stringToDate(result.get("planBeginDatetime").toString(), "yyyy-MM-dd HH:mm:ss");
            Date beginDate = DateUtil.stringToDate(result.get("planBeginDatetime").toString(), "yyyy-MM-dd");
            //如果指定时间的0点小于开始时间，则使用开始时间计算
            Date startTime = executeDate.equals(beginDate) ? beginDateTime : DateUtil.getDateAfterRedSecond(executeDate, 1);
            //Date endTime = DateUtil.stringToDate(result.get("planEndDatetime").toString());
            Date eTime = null;
            if (result.get("planEndDatetime") != null) {
                eTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) result.get("planEndDatetime"));
            }
            Date endTime = result.get("planEndDatetime") == null ? executeEndDateTime : (eTime.compareTo(executeEndDateTime) >= 0 ? executeEndDateTime : eTime);
            CronDescriber cronDescriber = JSONObject.parseObject((String) result.get("CRON_DESCRIBER"), CronDescriber.class);
            String expression = CronUtil.createCronExpression(cronDescriber, null);
            CronExpression cronExpression = null;
            try {
                cronExpression = new CronExpression(expression);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (startTime.equals(beginDateTime) && result.get("TIMEMODE").equals("1")) {
                startTime = executeDate;
            }
            startTime = cronExpression.getNextValidTimeAfter(startTime);
            /*if (startTime.equals(DateUtil.getDateAfter(beginDateTime, 1)) || startTime.after(executeEndDateTime)) {//执行时间与创建时间一致.非间隔时间表达式会不包含.会向前推一天,需要判断后手动回
                startTime = DateUtil.getDateBefore(startTime, 1);
            }*/


            while (startTime.before(executeEndDateTime) && (null == result.get("planEndDatetime") || startTime.before(endTime))) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("execDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime));


                String oralCode = new StringBuffer("j_").append(result.get("medicalNum")).append((new SimpleDateFormat("yyyyMMddHHmmss").format(startTime)).substring(2)).append(result.get("orderNo")).toString();
                String specialUsageFlag = result.get("administrationId") == null ? null : taskExecuteMapper.querySpecialUsage(result.get("administrationId").toString());
                boolean specialFlag = true;
                if (org.apache.commons.lang3.StringUtils.isNotBlank(specialUsageFlag) && startTime.before(beginDateTime)) {
                    specialFlag = false;
                }
                if (specialFlag) {
                    map.put("qrCode", oralCode);
                    qrCodeList.add(map);
                }
                startTime = DateUtil.increasedSeconds(startTime, Integer.parseInt((String) result.get("exeCycleStamp")));
                //map.put("qrCode", oralCode);
                //qrCodeList.add(map);

            }
        }
        result.put("qrCodeList", qrCodeList);


    }


    @Override
    public Result getWorkLogCount(String inpatNum, String dateTime) {
        List<Map<String, String>> list = taskExecuteMapper.queryExecuteDetailWorkLogCount(inpatNum, dateTime);
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("allNum", "0");
        resultMap.put("unfinishNum", "0");
        resultMap.put("finishNum", "0");
        Integer sum = 0;
        for (Map<String, String> map : list) {
            if (map.get("title") != null && map.get("title").equals("finish")) {
                resultMap.put("finishNum", map.get("count") == null ? "0" : map.get("count"));
            } else if (map.get("title") != null && map.get("title").equals("unfinish")) {
                resultMap.put("unfinishNum", map.get("count") == null ? "0" : map.get("count"));
            }
            sum += Integer.parseInt(map.get("count") == null ? "0" : map.get("count"));
        }
        resultMap.put("allNum", String.valueOf(sum));
        return ResultGenerator.genOkResult(resultMap);
    }

    @Override
    public Result getEmrFileByCtlId(String qrCode, String ctlId) {
        return null;
    }

    @Override
    public Result getEmrFileByqrCode(String qrCode) {
        return screenQrCode(qrCode, null, null);
    }

    /**
     * 根据预生成的qrcode扫码创建任务
     *
     * @param qrcode
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result generatTaskByQrcode(String qrcode) {
        try {
            boolean jumpPrintFlag = false;
            if (qrcode.contains("notprint_")) {
                jumpPrintFlag = true;
                qrcode = qrcode.replaceAll("notprint_", "");
            }
            boolean finalQrcode2 = jumpPrintFlag;

            long startMill = System.currentTimeMillis();
            if (!CollectionUtils.isEmpty(taskExecuteBatchMapper.selectBatchEntityByQrcode(qrcode)) && !qrcode.startsWith("k_")) {
                //return true;
                return ResultGenerator.genOkResult();
            }
            boolean isSet = redisUtil.setNx(qrcode, "GET LOCK", 1, TimeUnit.SECONDS);
            log.info("redisUtil.setNx()：" + isSet);
            if (!isSet) {
                //return false;
                return ResultGenerator.genFailedResult("任务执行中，请重试");
            }
            long secondMill = System.currentTimeMillis();
            //1.根据条码获取使用日期+时间，住院号,同时获取间隔时间的医嘱
            //2.根据条码中的住院号，使用日期+时间查询所有未停止的医嘱，医嘱起始时间必须小于该条码时间
            //3.计算每个医嘱在该时间端的使用批次
            //4.使用createNexTaskNodeList创建所有医嘱的
            if (qrcode.startsWith("k_")) {
                //口服药条码生成任务
                String inpatNum = qrcode.substring(2, qrcode.length() - 12) + "-1";
                String executeDatetimeStr = qrcode.substring(qrcode.length() - 12);
                Date executeTime = DateUtil.stringToDate(executeDatetimeStr, "yyMMddHHmmss");
                Date startDate = DateUtil.stringToDate(executeDatetimeStr.substring(0, 6), "yyMMdd");
                Date endTime = DateUtil.getDateAfter(DateUtil.stringToDate(executeDatetimeStr.substring(0, 6), "yyMMdd"), 1);
                String executeTimeStr = qrcode.substring(qrcode.length() - 6);
                //查询已生成的任务
                List<String> taskQrCodeList = oralOrdersRelationMapper.selectByOralCodeCount(qrcode);
                List<String> orderNos = taskQrCodeList.stream().filter(StringUtils::isNotEmpty).map(x -> x.split(executeDatetimeStr)[1]).collect(Collectors.toList());
                //查询已打印未生成任务的医嘱
                List<String> unPrintOrderNos = oralOrdersRelationMapper.selectUnPrintOrderNo(orderNos, qrcode);
                List<String> genFlag = oralOrdersRelationMapper.selectByOralCodeCount(qrcode);
                //如果是已打印并且未生成的医嘱则生成，否则不生成

                //查询指定时间、查询间隔时间
                List<Map<String, String>> orderExecs = taskExecuteMapper.selectOrderByQrcode(inpatNum, endTime, executeTimeStr.substring(0, 2) + ":" + executeTimeStr.substring(2, 4) + ":" + executeTimeStr.substring(4));
                List<TaskExecuteBatchEntity> list = new CopyOnWriteArrayList<>();
                List<TaskExecuteBatchEntity> relationList = new CopyOnWriteArrayList<>();
                long thirdMill = System.currentTimeMillis();
                AtomicInteger i = new AtomicInteger(1);
                orderExecs.stream().forEach(map -> {
                    if (((genFlag == null || genFlag.size() == 0) && finalQrcode2) || unPrintOrderNos.contains(String.valueOf(map.get("ORDER_NO")))) {
                        //判断该医嘱是否打印，如果未打印则不生成任务
                        log.info("当前医嘱序号：：：：：：" + i.getAndIncrement());
                        log.info("当前医嘱编号：：：：：：" + map.get("INPATORDERDATA_ID"));
                        //长期医嘱，频次间隔创建任务
                        if (null != map.get("TIMEMODE") && "1".equals(map.get("TIMEMODE")) && map.get("ORDER_CLASS_ID").equals("1")) {
                            CronExpression cronExpression = null;
                            CronDescriber cronDescriber = JSONObject.parseObject(map.get("CRON_DESCRIBER"), CronDescriber.class);
                            String expression = CronUtil.createCronExpression(cronDescriber, null);
                            try {
                                cronExpression = new CronExpression(expression);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            Date endDateTime = DateUtil.stringToDate(map.get("PLAN_END_DATETIME"), "yyyy-MM-dd HH:mm:ss");
                            Date beginDateTime = DateUtil.stringToDate(map.get("PLAN_BEGIN_DATETIME"), "yyyy-MM-dd HH:mm:ss");
                            Date beginDate = DateUtil.stringToDate(map.get("START_TIME"), "yyyy-MM-dd");
                            //如果指定时间的0点小于开始时间，则使用开始时间计算
                            Date startTime = startDate.equals(beginDate) ? beginDateTime : DateUtil.getDateAfterRedSecond(startDate, 1);
                            startTime = cronExpression.getNextValidTimeAfter(startTime);
                            while ((null == map.get("PLAN_END_DATETIME") || startTime.before(endDateTime)) && startTime.before(endTime)) {
                                if (executeTime.equals(startTime)) {
                                    //查询最大批次
                                    Map<String, String> taskMap = taskExecuteMapper.getEmrFileIdFromExec(map.get("INPATORDERDATA_ID"));
                                    Map<String, String> injectMap = taskExecuteMapper.getMoveInjectTaskIdAndNodeId(map.get("INPATORDERDATA_ID"));
                                    if (null == injectMap) {
                                        return;
                                    }
                                    TaskNodeEntity taskNodeEntity = new TaskNodeEntity();
                                    taskNodeEntity.setTaskId(injectMap.get("TASK_ID"));
                                    taskNodeEntity.setTaskNodeId(injectMap.get("TASK_NODE_ID"));
                                    OrdersFileIndexEntity emrFileIndex;
                                    EmrFile emrFile = fileIndexService.getFileIndex(taskMap.get("EMR_FILE_ID"));
                                    emrFileIndex = emrFile.getEmrFileIndexEntity();
                                    String qrCodeSerialNo = "kr_" + inpatNum.replace("-1", "") + executeDatetimeStr + String.valueOf(map.get("ORDER_NO"));
                                    TaskExecuteBatchEntity taskExecuteBatchEntity = createTaskExecute(injectMap, map.get("INPATORDERDATA_ID"),
                                            TaskEnum.UNEXECUTED.getValue(), taskNodeEntity, emrFileIndex, executeTime, qrCodeSerialNo, null);
                                    relationList.add(taskExecuteBatchEntity);
                                    list.add(taskExecuteBatchEntity);
                                }
                                startTime = DateUtil.increasedSeconds(startTime, Integer.parseInt(map.get("EXE_CYCLE_STAMP")));
                            }
                        } else if (map.get("ORDER_CLASS_ID").equals("1")) {
                            //查询最大批次
                            Map<String, String> taskMap = taskExecuteMapper.getEmrFileIdFromExec(map.get("INPATORDERDATA_ID"));
                            Map<String, String> injectMap = taskExecuteMapper.getMoveInjectTaskIdAndNodeId(map.get("INPATORDERDATA_ID"));
                            if (null == injectMap) {
                                return;
                            }
                            TaskNodeEntity taskNodeEntity = new TaskNodeEntity();
                            taskNodeEntity.setTaskId(injectMap.get("TASK_ID"));
                            taskNodeEntity.setTaskNodeId(injectMap.get("TASK_NODE_ID"));
                            OrdersFileIndexEntity emrFileIndex;
                            EmrFile emrFile = fileIndexService.getFileIndex(taskMap.get("EMR_FILE_ID"));
                            emrFileIndex = emrFile.getEmrFileIndexEntity();
                            String qrCodeSerialNo = "kr_" + inpatNum.replace("-1", "") + executeDatetimeStr + String.valueOf(map.get("ORDER_NO"));
                            TaskExecuteBatchEntity taskExecuteBatchEntity = createTaskExecute(injectMap, map.get("INPATORDERDATA_ID"),
                                    TaskEnum.UNEXECUTED.getValue(), taskNodeEntity, emrFileIndex, executeTime, qrCodeSerialNo, null);
                            relationList.add(taskExecuteBatchEntity);
                            list.add(taskExecuteBatchEntity);
                        } else {
                            //临时医嘱
                            Map<String, String> taskMap = taskExecuteMapper.getEmrFileIdFromExec(map.get("INPATORDERDATA_ID"));
                            Map<String, String> injectMap = taskExecuteMapper.getMoveInjectTaskIdAndNodeId(map.get("INPATORDERDATA_ID"));
                            if (null == injectMap) {
                                return;
                            }
                            TaskNodeEntity taskNodeEntity = new TaskNodeEntity();
                            taskNodeEntity.setTaskId(injectMap.get("TASK_ID"));
                            taskNodeEntity.setTaskNodeId(injectMap.get("TASK_NODE_ID"));
                            OrdersFileIndexEntity emrFileIndex;
                            EmrFile emrFile = fileIndexService.getFileIndex(taskMap.get("EMR_FILE_ID"));
                            emrFileIndex = emrFile.getEmrFileIndexEntity();
                            String qrCodeSerialNo = "kr_" + inpatNum.replace("-1", "") + executeDatetimeStr + String.valueOf(map.get("ORDER_NO"));
                            TaskExecuteBatchEntity taskExecuteBatchEntity = createTaskExecute(injectMap, map.get("INPATORDERDATA_ID"),
                                    TaskEnum.UNEXECUTED.getValue(), taskNodeEntity, emrFileIndex, executeTime, qrCodeSerialNo, null);
                            list.add(taskExecuteBatchEntity);
                            relationList.add(taskExecuteBatchEntity);

                        }
                    }
                });
                long fourthMill = System.currentTimeMillis();
                List<Map<String, Object>> listMap = new CopyOnWriteArrayList<>();
                String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
//            String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
                list.stream().forEach(x -> {
                    Map<String, Object> entityMap = new HashMap<>();
                    if (null == x) return;
                    x.setExecutePersonId(userId);
                    entityMap.put("taskExecuteDetailEntity", x);
                    entityMap.put("userId", userId);
                    listMap.add(entityMap);
                });
                long firthMill = System.currentTimeMillis();
                nursePatientOrderService.createNextTaskNodeList(listMap, "");
                long sixMill = System.currentTimeMillis();
                String wardDeptId = patientMapper.queryPatientInfo(inpatNum).get("wardDeptId");
                for (TaskExecuteBatchEntity x : relationList) {
                    OralOrdersRelationEntity oralOrdersRelationEntity = new OralOrdersRelationEntity();//二维码关联医嘱对象
                    oralOrdersRelationEntity.setCreateTime(new Date());
                    oralOrdersRelationEntity.setOralOrdersRelationId(UUIDUtil.randomString());
                    oralOrdersRelationEntity.setQrTime(executeDatetimeStr.substring(0, 6));
                    oralOrdersRelationEntity.setQrCode(qrcode);
                    oralOrdersRelationEntity.setInpatNum(inpatNum);
                    //                    oralOrdersRelationEntity.setFreq(item.get("freq").toString());
                    oralOrdersRelationEntity.setFreqTime(executeDatetimeStr.substring(6, 8) + ":" + executeDatetimeStr.substring(8, 10) + ":" + executeDatetimeStr.substring(10));
                    oralOrdersRelationEntity.setWardDeptId(wardDeptId);
                    oralOrdersRelationEntity.setInpatorderdataId(x.getInpatorderdataId());
                    oralOrdersRelationEntity.setTaskQrCode(x.getQrCode());
//                oralOrdersRelationEntity.setDelete("0");
                    oralOrdersRelationMapper.insert(oralOrdersRelationEntity);
                }
                long sevenMill = System.currentTimeMillis();
                log.info("口服药时间耗时计算：：：：：：：：：：：：：：：：：：：：：{}ms", sevenMill - startMill);
                log.info("判断消耗时间：：：：：：：：：：：：：：：：：：：：：{}ms", secondMill - startMill);
                log.info("间隔计算前消耗时间：：：：：：：：：：：：：：：：：：：：：{}ms", thirdMill - secondMill);
                log.info("间隔时间计算消耗时间：：：：：：：：：：：：：：：：：：：：：{}ms", fourthMill - thirdMill);
                log.info("调用医生端消耗时间：：：：：：：：：：：：：：：：：：：：：{}ms", sixMill - firthMill);
                log.info("保存任务与口服药条码关系消耗时间：：：：：：：：：：：：：：：：：：：：：{}ms", sevenMill - sixMill);
            } else if (qrcode.length() == 14 && isNumeric(qrcode)) {
                //静配中心条码生成任务
                //1.先找到idr.static_center中是否存在该条码
                StaticCenterEntity staticCenterEntity = staticCenterMapper.queryPersonIdByBarCode(qrcode, "0");
                if (null == staticCenterEntity) {
                    //return true;
                    throw new RuntimeException("静配中心未提供条码!");
                }
                //2.查询该条码后获取用药日期+时间
                String inpatNum = staticCenterEntity.getInpatNum();
                String executeTimeStr = staticCenterEntity.getUseDate().replaceAll("-", "") + staticCenterEntity.getUseTime().replace(":", "") + "00";
                Date executeTime = DateUtil.stringToDate(executeTimeStr, "yyyyMMddHHmmss");
                String orderNo = staticCenterEntity.getOrderNo();
                //根据住院号+orderNo查询对应医嘱，和对应的emrFileId
                Map<String, String> orderMap = taskExecuteBatchMapper.queryOrdersByInpat(inpatNum, orderNo);
                if (null == orderMap) {
                    //return true;
                    throw new RuntimeException("医嘱已停止!");
                }
                Map<String, String> taskMap = taskExecuteMapper.getEmrFileIdFromExec(orderMap.get("INPATORDERDATA_ID"));
                Map<String, String> injectMap = taskExecuteMapper.getMoveInjectTaskIdAndNodeId(orderMap.get("INPATORDERDATA_ID"));
                if (null == injectMap) {
                    throw new RuntimeException("未找到对应任务节点!");
                }
                TaskNodeEntity taskNodeEntity = new TaskNodeEntity();
                taskNodeEntity.setTaskId(injectMap.get("TASK_ID"));
                taskNodeEntity.setTaskNodeId(injectMap.get("TASK_NODE_ID"));

                EmrFile emrFile = fileIndexService.getFileIndex(taskMap.get("EMR_FILE_ID"));
                OrdersFileIndexEntity emrFileIndex = emrFile.getEmrFileIndexEntity();
                String qrCodeSerialNo = "j_" + inpatNum.replace("-1", "") + executeTimeStr.substring(2) + orderNo;
                //3.生成任务
                TaskExecuteBatchEntity taskExecuteBatchEntity = createTaskExecute(injectMap, orderMap.get("INPATORDERDATA_ID"),
                        TaskEnum.UNEXECUTED.getValue(), taskNodeEntity, emrFileIndex, executeTime, qrCodeSerialNo, qrcode);
                long thirdMill = System.currentTimeMillis();
                //4.根据频次创建任务，调用医生端
                nursePatientOrderService.createNextTaskNode(injectMap.get("TASK_EXECUTE_DETAIL_ID"), taskExecuteBatchEntity.getBatchNo() == null ? 1 : (taskExecuteBatchEntity.getBatchNo().intValue() + 1), emrFileIndex.getDoctorId(), "", "", DateUtil.dateToString(executeTime, "yyyy-MM-dd HH:mm:ss"), qrCodeSerialNo, null);
                long sixMill = System.currentTimeMillis();
                //5.根据频次和医嘱id更新所有符合该数据的bar_code
                //生成任务后更改STATIC_CENTER表中的状态
                staticCenterMapper.updateStaticCenterByBarCode(qrcode);
                long sevenMill = System.currentTimeMillis();
                log.info("静配条码时间耗时计算：：：：：：：：：：：：：：：：：：：：：{}ms", sevenMill - startMill);
                log.info("判断消耗时间：：：：：：：：：：：：：：：：：：：：：{}ms", secondMill - startMill);
                log.info("调用医生端前消耗时间：：：：：：：：：：：：：：：：：：：：：{}ms", thirdMill - secondMill);
                log.info("调用医生端消耗时间：：：：：：：：：：：：：：：：：：：：：{}ms", sixMill - thirdMill);
                log.info("更新静配消耗时间：：：：：：：：：：：：：：：：：：：：：{}ms", sevenMill - sixMill);
            } else if (qrcode.startsWith("y_")) {
                //输液单扫码
                //1、根据二维码获取住院号、频次时间、医嘱编号
                String qrCodes[] = qrcode.split("_");
                String medicalNum = qrCodes[1].substring(0, qrCodes[1].length() - 14);
                String inpatNum = medicalNum + "-1";
                String executeTimeStr = qrCodes[1].substring(qrCodes[1].length() - 14);
                String orderNo = qrCodes[2];
                Date executeTime = DateUtil.stringToDate(executeTimeStr, "yyyyMMddHHmmss");
                //2、根据qrcode中住院号和医嘱编号查询组医嘱中的sub_no=1的医嘱信息
                //根据住院号+orderNo查询对应医嘱，和对应的emrFileId
                Map<String, String> orderMap = taskExecuteBatchMapper.queryOrdersByInpat(inpatNum, orderNo);
                if (null == orderMap) {
                    //return true;
                    throw new RuntimeException("医嘱已停止!");
                }
                Map<String, String> taskMap = taskExecuteMapper.getEmrFileIdFromExec(orderMap.get("INPATORDERDATA_ID"));
                Map<String, String> injectMap = taskExecuteMapper.getMoveInjectTaskIdAndNodeId(orderMap.get("INPATORDERDATA_ID"));
                if (null == injectMap) {
                    //return true;
                    throw new RuntimeException("未找到对应任务节点!");
                }
                if (ConstsEnum.TASK_NAME_WHLC.getName().equals(injectMap.get("TASK_NAME"))) {
                    TaskExecuteBatchEntity temp = new TaskExecuteBatchEntity();
                    temp.setQrCode(qrcode);
                    int count = taskExecuteBatchMapper.selectCount(temp);
                    String times = printMarkMapper.countByQrCode(qrcode, NurseEnum.PRINT_THREE.getIndex());
                    if (count == 0 && StringUtils.isBlank(times)) {
                        throw new RuntimeException("此任务未打印!");
                    }
                }
                TaskNodeEntity taskNodeEntity = new TaskNodeEntity();
                taskNodeEntity.setTaskId(injectMap.get("TASK_ID"));
                taskNodeEntity.setTaskNodeId(injectMap.get("TASK_NODE_ID"));

                EmrFile emrFile = fileIndexService.getFileIndex(taskMap.get("EMR_FILE_ID"));
                OrdersFileIndexEntity emrFileIndex = emrFile.getEmrFileIndexEntity();
                String qrCodeSerialNo = "y_" + medicalNum + executeTimeStr + "_" + orderNo;
                //3.生成任务
                TaskExecuteBatchEntity taskExecuteBatchEntity = createTaskExecute(injectMap, orderMap.get("INPATORDERDATA_ID"),
                        TaskEnum.UNEXECUTED.getValue(), taskNodeEntity, emrFileIndex, executeTime, qrCodeSerialNo, null);
                long sixMill = System.currentTimeMillis();
                //4.根据频次创建任务，调用医生端
                nursePatientOrderService.createNextTaskNode(injectMap.get("TASK_EXECUTE_DETAIL_ID"), taskExecuteBatchEntity.getBatchNo() == null ? 1 : (taskExecuteBatchEntity.getBatchNo().intValue() + 1), emrFileIndex.getDoctorId(), "", "", DateUtil.dateToString(executeTime, "yyyy-MM-dd HH:mm:ss"), qrCodeSerialNo, null);
                long sevenMill = System.currentTimeMillis();
                log.info("输液条码时间耗时计算：：：：：：：：：：：：：：：：：：：：：{}ms", sevenMill - startMill);
                log.info("判断消耗时间：：：：：：：：：：：：：：：：：：：：：{}ms", secondMill - startMill);
                log.info("调用医生端前消耗时间：：：：：：：：：：：：：：：：：：：：：{}ms", sixMill - secondMill);
                log.info("调用医生端消耗时间：：：：：：：：：：：：：：：：：：：：：{}ms", sevenMill - sixMill);
            }
        } catch (Exception ex) {
            log.error("标本采集出错", ex);
            return ResultGenerator.genFailedResult(ex.getMessage());
        }
        return ResultGenerator.genOkResult();
    }

    private void executeTask(List<Map<String, String>> orderExecs, String qrcode, String type, List<TaskExecuteBatchEntity> list) {
        AtomicInteger i = new AtomicInteger(1);
        orderExecs.forEach(map -> {
            log.info("当前医嘱序号：：：：：：" + i.getAndIncrement());
            log.info("当前医嘱编号：：：：：：" + map.get("INPATORDERDATA_ID"));
            //长期医嘱，频次间隔创建任务
            if (null != map.get("TIMEMODE")) {
                if ("0".equals(map.get("TIMEMODE"))) {
                    createNextNode(qrcode, map, type, list);
                } else if ("1".equals(map.get("TIMEMODE"))) {
                    //长期医嘱，定时创建任务
                    createByTimeNextNode(qrcode, map, type, list);
                }
            }
        });
    }

    public static boolean isNumeric(String str) {
        String bigStr;
        try {
            bigStr = new BigDecimal(str).toString();
        } catch (Exception e) {
            return false;//异常 说明包含非数字。
        }
        return true;
    }

    void createByTimeNextNode(String qrcode, Map<String, String> map, String type, List<TaskExecuteBatchEntity> list) {
        //创建间隔时间任务
        try {
            Date startTime = DateUtil.stringToDate(map.get("START_TIME"));
            Map<String, String> taskMap = taskExecuteMapper.getEmrFileIdFromExec(map.get("INPATORDERDATA_ID"));
            Integer batchNo = Integer.valueOf(qrcode.substring(qrcode.indexOf("_") + 1, qrcode.lastIndexOf("_")));
            Date nextExecDate = new Date(((batchNo - 1) * 1000 * Integer.parseInt(map.get("EXE_CYCLE_STAMP"))) + startTime.getTime());
            TaskExecuteBatchEntity taskBatch = taskExecuteBatchMapper.queryTaskBatch(batchNo, map.get("INPATORDERDATA_ID"));
            if (null != taskBatch) {
                return;
            }
            log.info("emrFileId = " + taskMap.get("EMR_FILE_ID"));
            //获取文书
            OrdersFileIndexEntity emrFileIndex;
            try {
                EmrFile emrFile = fileIndexService.getFileIndex(taskMap.get("EMR_FILE_ID"));
                emrFileIndex = emrFile.getEmrFileIndexEntity();
            } catch (Exception e) {
                //计算下一个间隔任务时间
                log.error(e.getMessage());
                return;
            }
            log.info("医嘱id：" + map.get("INPATORDERDATA_ID"));
            Map<String, String> injectMap = taskExecuteMapper.getMoveInjectTaskIdAndNodeId(map.get("INPATORDERDATA_ID"));
            if (null == injectMap) {
                return;
            }
            TaskNodeEntity taskNodeEntity = new TaskNodeEntity();
            taskNodeEntity.setTaskId(injectMap.get("TASK_ID"));
            taskNodeEntity.setTaskNodeId(injectMap.get("TASK_NODE_ID"));
            //执行任务流程
            TaskExecuteBatchEntity taskExecuteBatchEntity = createTaskExecute(taskMap, map.get("INPATORDERDATA_ID"),
                    TaskEnum.UNEXECUTED.getValue(), taskNodeEntity, emrFileIndex, nextExecDate, qrcode, null);
            //触发下一个任务节点
            if (type.equals("single"))
                nursePatientOrderService.createNextTaskNode(taskMap.get("TASK_EXECUTE_DETAIL_ID"), batchNo, emrFileIndex.getDoctorId(), "", "", DateUtil.dateToString(nextExecDate, "yyyy-MM-dd HH:mm:ss"), "", null);
            else
                list.add(taskExecuteBatchEntity);
            Date finallyDate = nextExecDate;
            if (null != finallyDate)
                taskExecuteMapper.updateOrderExecuteTime(map.get("INPATORDERDATA_ID"), finallyDate);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 长期医嘱，按频次创建任务
     *
     * @param qrcode
     * @param map
     */
    public void createNextNode(String qrcode, Map<String, String> map, String type, List<TaskExecuteBatchEntity> list) {
        try {
            Integer batchNo = Integer.valueOf(qrcode.substring(qrcode.indexOf("_") + 1, qrcode.lastIndexOf("_")));
            Map<String, String> taskMap = taskExecuteMapper.getEmrFileIdFromExec(map.get("INPATORDERDATA_ID"));
            CronExpression cronExpression = null;
            AtomicInteger hourNum = new AtomicInteger(0);
            AtomicInteger weekNum = new AtomicInteger(0);
            CronDescriber cronDescriber = JSONObject.parseObject(map.get("CRON_DESCRIBER"), CronDescriber.class);
            hourNum.set(cronDescriber.getSpecifiedHourNum());
            weekNum.set(cronDescriber.getSpecifiedDowNum());
            String expression = CronUtil.createCronExpression(cronDescriber, null);
            cronExpression = new CronExpression(expression);

            int startTimes = 0;
            Date startNextDay = DateUtil.getDateAfter(DateUtil.stringToDate(map.get("PLAN_BEGIN_DATETIME"), "yyyy-MM-dd"), 1);
            Date startDate = cronExpression.getNextValidTimeAfter(DateUtil.stringToDate(map.get("PLAN_BEGIN_DATETIME")));
            Map<Integer, Date> startMap = new HashMap<>();
            while (null != startDate && startDate.before(startNextDay)) {
                startTimes++;
                startMap.put(startTimes, startDate);
                startDate = cronExpression.getNextValidTimeAfter(startDate);
            }

            int cycleAllNum = hourNum.get() * (weekNum.get() == 0 ? 1 : weekNum.get()); //Q4H = 6 , TID = 3 , TIW = 3
            int cycleNum = cycleAllNum / Integer.valueOf(map.get("EXE_NUMBER"));//Q4H = 6 , TID = 1 , TIW = 1 || EXE_CYCLE_STAMP（Q4H = 14400 , TID = 86400 , TIW = 604800)
            //Q4H = 开始到现在的间隔时间/间隔周期/按日或周执行期间次数*单位总次数

            Date nextExecDate;
            if (batchNo <= startTimes) {
                nextExecDate = startMap.get(batchNo);
            } else {
                //计算批次对应的执行时间
                //1.获得该批次与第一次执行的时间差，天数
                //2.根据天数取余获得今天执行第几次
                //3.循环执行下一个批次（天数+开始时间），直到满足第二部的取余数
                nextExecDate = new Date(((((batchNo - startTimes - 1) / cycleAllNum)) * cycleNum * 1000 * Long.parseLong(map.get("EXE_CYCLE_STAMP"))) + startDate.getTime());
                for (int i = (batchNo - startTimes) % cycleAllNum; i < cycleAllNum
                        //如果是当天第一个节点则不需要，因为上面已经执行了
                        && (batchNo - startTimes) % cycleAllNum != 1; i++) {
                    if ((batchNo - startTimes) % cycleAllNum == 0 && i == (cycleAllNum - startTimes)) {
                        continue;
                    }
                    nextExecDate = cronExpression.getNextValidTimeAfter(nextExecDate);
                }
            }

            TaskExecuteBatchEntity taskBatch = taskExecuteBatchMapper.queryTaskBatch(batchNo, map.get("INPATORDERDATA_ID"));
            if (null != taskBatch) {
                return;
            }
            log.info("emrFileId ： " + taskMap.get("EMR_FILE_ID"));
            OrdersFileIndexEntity emrFileIndex;
            try {
                EmrFile emrFile = fileIndexService.getFileIndex(taskMap.get("EMR_FILE_ID"));
                emrFileIndex = emrFile.getEmrFileIndexEntity();
            } catch (Exception e) {
                log.error(e.getMessage());
                return;
            }
            log.info("医嘱id ： " + map.get("INPATORDERDATA_ID"));
            Map<String, String> injectMap = taskExecuteMapper.getMoveInjectTaskIdAndNodeId(map.get("INPATORDERDATA_ID"));
            if (null == injectMap) {
                return;
            }
            TaskNodeEntity taskNodeEntity = new TaskNodeEntity();
            taskNodeEntity.setTaskId(injectMap.get("TASK_ID"));
            taskNodeEntity.setTaskNodeId(injectMap.get("TASK_NODE_ID"));
            //执行任务流程
            TaskExecuteBatchEntity taskExecuteBatchEntity = createTaskExecute(taskMap, map.get("INPATORDERDATA_ID"),
                    TaskEnum.UNEXECUTED.getValue(), taskNodeEntity, emrFileIndex, nextExecDate, qrcode, null);
            //触发下一个任务节点
            if (type.equals("single"))
                nursePatientOrderService.createNextTaskNode(taskMap.get("TASK_EXECUTE_DETAIL_ID"), batchNo, emrFileIndex.getDoctorId(), "", "", DateUtil.dateToString(nextExecDate, "yyyy-MM-dd HH:mm:ss"), "", null);
            else
                list.add(taskExecuteBatchEntity);
            Date finallyDate = nextExecDate;
            if (null != finallyDate)
                taskExecuteMapper.updateOrderExecuteTime(map.get("INPATORDERDATA_ID"), finallyDate);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 生成任务执行
     *
     * @param inpatorderdataId 医嘱id
     * @param emrFileIndex     文书
     * @param barCode
     * @return
     */
    public TaskExecuteBatchEntity createTaskExecute(Map<String, String> taskMap, String inpatorderdataId, String execeted, TaskNodeEntity taskNodeEntity,
                                                    OrdersFileIndexEntity emrFileIndex, Date date, String qrCode, String barCode) {
        TaskExecuteBatchEntity taskExecuteBatchEntity = taskExecuteBatchMapper.selectBatchCountByQrcode(qrCode);
        if (null != taskExecuteBatchEntity) {
            return taskExecuteBatchEntity;
        }
        //查询task_execute_id,task_execute_detail_id,node_name
        String taskBatchId = UUIDUtil.randomString();
        TaskExecuteBatchEntity taskExecuteBatch = new TaskExecuteBatchEntity();
        //计算当前应该生成的批次，并查询出当前批次-1的serial_no最大的数据，判断status是否是1
        taskExecuteBatch.initAdd();
        taskExecuteBatch.setInpatorderdataId(inpatorderdataId);
        taskExecuteBatch.setTaskExecuteDetailId(taskMap.get("TASK_EXECUTE_DETAIL_ID"));
        taskExecuteBatch.setTaskExecuteId(taskMap.get("TASK_EXECUTE_ID"));
        taskExecuteBatch.setTaskNodeId(taskNodeEntity.getTaskNodeId());
        taskExecuteBatch.setSerialNo(1);
        taskExecuteBatch.setStartDatetime(new Timestamp(date.getTime()));
        taskExecuteBatch.setStopDatetime(new Timestamp(date.getTime()));
        taskExecuteBatch.setEmrFileId(emrFileIndex.getEmrFileId());
        taskExecuteBatch.setStatus(execeted);
        taskExecuteBatch.setExecutePersonId(emrFileIndex.getDoctorId());
        taskExecuteBatch.setQrCode(qrCode);
        taskExecuteBatch.setNodeName(taskMap.get("node_name"));
        taskExecuteBatch.setTaskBatchId(taskBatchId);
        taskExecuteBatch.setBatchFlag("1");
        taskExecuteBatch.setBarCode(barCode);
        taskExecuteBatchMapper.insert(taskExecuteBatch);
        taskExecuteBatchMapper.updateBatchNo(taskExecuteBatch.getTaskBatchId(), inpatorderdataId);
        return taskExecuteBatchMapper.selectBatchCountByQrcode(qrCode);
    }

    @Override
    public String checkOrderStatus(String inpatOrderDataId, String type) {
//      1.根据医嘱id查询医嘱的状态
        Map<String, Object> orderMap = taskExecuteBatchMapper.selectOrderStatusByInpatorderdataId(inpatOrderDataId);
        //复核状态
        String execStatusHis = (String) orderMap.get("EXEC_STATUS_HIS");
        //停止复核时间
        Date nurseStopDatetime = (Date) orderMap.get("NURSE_STOP_DATETIME");
        //预计结束时间
        Date planEndDatetime = (Date) orderMap.get("PLAN_END_DATETIME");
        //医嘱执行状态
        String execStatus = (String) orderMap.get("EXEC_STATUS");
        //医嘱药品
        String ordersItem = (String) orderMap.get("ORDERS_ITEM");
        String returnStr = "";
//      2.根据医嘱判断是否新开复核
        if (null == execStatusHis || Integer.valueOf(execStatusHis) < 2) {
            returnStr = "医嘱未复核，无法执行";
        }
        //      3.判断医嘱执行状态是不是3停止,4作废,8删除,9取消
        if (StringUtils.isNotEmpty(execStatusHis) && "4".equals(execStatusHis)) {
            returnStr = "医嘱无效，无法执行";
        }
//      4.根据医嘱判断是否已停止复核
        if (null != nurseStopDatetime && null != planEndDatetime) {
//          5.判断医嘱的停止复核时间是否小于预计结束时间，如果小于预计结束时间则取预计结束时间进行判断
            Date stopDateTime = nurseStopDatetime.before(planEndDatetime) ? planEndDatetime : nurseStopDatetime;
//          6.判断该医嘱停止复核后是不是真的不能执行
            if (OrderStatusEnum.ORDER_STOP_HIS.getValue().equals(execStatusHis) && stopDateTime.before(DateUtil.localDateTime2Date(LocalDateTime.now()))) {
                returnStr = "医嘱已停止，无法执行";
            }
        }
//      7.返回医嘱实际状态并提示，如：XXXXX医嘱未复核，无法执行||XXXXX医嘱已停止，无法执行
        if (StringUtils.isNotEmpty(type) && type.equals("oralMedicine"))
            return new StringBuilder(ordersItem).append(returnStr).toString();
        return returnStr;
    }

    @Override
    public Result generatTaskNode(String qrCode) {
        Result result = generatTaskByQrcode(qrCode);
        return result;
        //return ResultGenerator.genOkResult(generatTaskByQrcode(qrCode));
    }

    /**
     * 终止功能
     *
     * @param stopTaskDTO
     * @return
     */
    public Result stopTask(StopTaskDTO stopTaskDTO) {
        //判断是哪个任务流程
        if ("0".equals(stopTaskDTO.getStatus()) || "1".equals(stopTaskDTO.getStatus())) {
            String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
            if ("服药".equals(stopTaskDTO.getFunMark())) {
                UserEntity userEntity = userMapper.queryUserId(userId);
                if (userEntity != null) {
                    return oralMedicineService.turnBack(stopTaskDTO.getWardDeptId(), stopTaskDTO.getQrCode(), new ArrayList<String>(Arrays.asList(stopTaskDTO.getInpatorderdataId().split(","))),
                            userEntity.getUserName(), VarCodeEnum.QT.getName().equals(stopTaskDTO.getReturnReason()) ? stopTaskDTO.getOtherReason() : stopTaskDTO.getReturnReason(), StateEnum.ZZ_TYPE.getValue());
                }
            } else if ("雾化".equals(stopTaskDTO.getFunMark())) {
                //判断是否有任务
                List<Map<String, Object>> taskList = taskExecuteMapper.queryTaskExecuteBatchByQrCode(stopTaskDTO.getQrCode(), null);
                if (CollectionUtils.isNotEmpty(taskList)) {
                    Map<String, Object> executeTaskMap = taskList.stream().filter(s -> "0".equals(s.get("status"))).findFirst().orElse(null);
                    if (executeTaskMap != null) {
                        String emrFileId = (String) executeTaskMap.get("emrFileId");
                        if (StringUtils.isNotBlank(emrFileId)) {
                            //更改文书
                            List<OrdersFileIndexDataDTO> fileData = ordersFileIndexDataMapper.selectDataByEmrFileId(emrFileId);
                            if (CollectionUtils.isNotEmpty(fileData)) {
                                fileData.stream().forEach(file -> {
                                    if (VarCodeEnum.WHCL.getVarCode().equals(file.getVarCode())) {
                                        taskExecuteMapper.updateAtomizationTerminationStatus("终止", "e487c1954b1b4230bbc50feee36d6065", emrFileId, file.getElementId());
                                        //终止
                                    } else if (VarCodeEnum.WHYWHSYY.getVarCode().equals(file.getVarCode())) {
                                        //根据elementId获取dataCode
                                        String dataCode = taskExecuteMapper.getDataCodeByElementId(file.getElementId(), stopTaskDTO.getReturnReason());
                                        taskExecuteMapper.updateAtomizationTerminationStatus(stopTaskDTO.getReturnReason(), dataCode, emrFileId, file.getElementId());
                                        //原因
                                    } else if (VarCodeEnum.QT.getVarCode().equals(file.getVarCode())) {
                                        //其他
                                        taskExecuteMapper.updateAtomizationTerminationStatus(stopTaskDTO.getOtherReason(), null, emrFileId, file.getElementId());
                                    }
                                });
                            }
                        }
                        //新增雾化终止数据
                        this.insertAtomizeMedReturn(stopTaskDTO, userId);
                        //执行到下一个终止节点
                        TaskExecuteDetailDTO executeDetailDTO = taskExecuteDetailMapper.queryTaskExecuteDetailInfo(stopTaskDTO.getQrCode());
                        nursePatientOrderService.createNextTaskNode(executeDetailDTO.getTaskExecuteDetailId(), executeDetailDTO.getBatchNo(), userId, executeDetailDTO.getGroupId() == null ? "" : executeDetailDTO.getGroupId(), "", null, stopTaskDTO.getQrCode(), TaskEnum.TASKSTOP.getValue());
                    }
                } else {
                    //任务未生成
                    this.insertAtomizeMedReturn(stopTaskDTO, userId);
                }
                return ResultGenerator.genOkResult("终止成功");

            } else if ("输液".equals(stopTaskDTO.getFunMark())) {
                return stopInfusion(stopTaskDTO, userId);
            } else if ("注射".equals(stopTaskDTO.getFunMark())) {
                return stopInjection(stopTaskDTO, userId);
            } else if ("肠内营养".equals(stopTaskDTO.getFunMark())) {
                return stopEnteralNutrition(stopTaskDTO, userId);
            }
        }
        return ResultGenerator.genFailedResult("此任务不能进行终止!");
    }

    /**
     * 输液终止
     *
     * @param stopTaskDTO
     * @param userId
     */
    public Result stopInfusion(StopTaskDTO stopTaskDTO, String userId) {
        //判断是否有任务
        List<Map<String, Object>> taskList = taskExecuteMapper.queryTaskExecuteBatchByQrCode(stopTaskDTO.getQrCode(), null);
        if (CollectionUtils.isNotEmpty(taskList)) {
            //判断节点是否在输液中心，并且是执行过输液巡视  最后一个节点
            Map<String, Object> executeTaskMap = taskList.stream().filter(s -> "0".equals(s.get("status"))).findFirst().orElse(null);
            //倒数第二个节点
            if (executeTaskMap != null) {
                String varCode = (String) executeTaskMap.get("varCode");
                String emrFileId = (String)executeTaskMap.get("emrFileId");
                String taskBatchId = (String) executeTaskMap.get("taskBatchId");
                /*if (StringUtils.isNotBlank(varCode) && VarCodeEnum.RWJD_SYZX.getVarCode().equalsIgnoreCase(varCode)) {
                    //输液中心
                    //如果当前节点在输液中心，上一个节点为输液巡视
                    Map<String, Object> syxsMap = taskList.stream().skip(taskList.size() - 2).findFirst().orElse(null);
                    String syxsVarCode = (String) syxsMap.get("varCode");
                    if (StringUtils.isNotBlank(syxsVarCode) && VarCodeEnum.RWJD_SYXS.getVarCode().equalsIgnoreCase(syxsVarCode)) {
                        //新增终止数据
                        this.insertAtomizeMedReturn(stopTaskDTO, userId);
                        //更新状态
                        taskExecuteMapper.updateTaskExecuteBatchById(userId, "1", taskBatchId);
                        return ResultGenerator.genOkResult("终止成功");
                        //输液巡视
                                /*if(StringUtils.isNotBlank(emrFileId)) {
                                    //更改文书
                                    List<OrdersFileIndexDataDTO> fileData = ordersFileIndexDataMapper.selectDataByEmrFileId(emrFileId);
                                    if(CollectionUtils.isNotEmpty(fileData)){
                                        fileData.stream().forEach(file->{
                                            if(VarCodeEnum.SYZZ.getVarCode().equals(file.getVarCode())){
                                                //终止
                                                String dataCode = taskExecuteMapper.getDataCodeByElementId(file.getElementId(),"终止");
                                                taskExecuteMapper.updateAtomizationTerminationStatus("终止",dataCode,emrFileId,file.getElementId());
                                            }
                                        });
                                    }
                                }*/
                //新增终止数据
                //this.insertAtomizeMedReturn(stopTaskDTO,userId);
                //执行到下一个终止节点
                //TaskExecuteDetailDTO executeDetailDTO = taskExecuteDetailMapper.queryTaskExecuteDetailInfo(stopTaskDTO.getQrCode());
                //nursePatientOrderService.createNextTaskNode(executeDetailDTO.getTaskExecuteDetailId(), executeDetailDTO.getBatchNo(), userId, executeDetailDTO.getGroupId() == null ? "" : executeDetailDTO.getGroupId(), "", null, stopTaskDTO.getQrCode());
                //}
                //} else
                if (StringUtils.isNotBlank(varCode) && (VarCodeEnum.RWJD_BFBYHD.getVarCode().equalsIgnoreCase(varCode)
                        || VarCodeEnum.RWJD_BFJYHD.getVarCode().equalsIgnoreCase(varCode)
                        || VarCodeEnum.RWJD_SYZX.getVarCode().equalsIgnoreCase(varCode))) {
                    //新增终止数据
                    this.insertAtomizeMedReturn(stopTaskDTO, userId);
                    //更新状态
                    taskExecuteMapper.updateTaskExecuteBatchById(userId, "1", taskBatchId, TaskEnum.TASKSTOP.getValue());
                    return ResultGenerator.genOkResult("终止成功");
                }else if(StringUtils.isNotBlank(varCode) && VarCodeEnum.RWJD_SYXS.getVarCode().equalsIgnoreCase(varCode)){
                    //return ResultGenerator.genOkResult("终止成功");
                    //0 封管 1 拔针
                    String operationStatus = stopTaskDTO.getOperationStatus();
                    //0 暂停  1 完成
                    String taskStatus = stopTaskDTO.getTaskStatus();
                    Map<String, Object> infusionExecutionMap = taskList.stream().filter(x->"0".equals(x.get("status"))).findFirst().orElse(null);
                    if(infusionExecutionMap!=null) {
                        String inpatorderdataId = (String)infusionExecutionMap.get("inpatorderdataId");
                        String batchNo = String.valueOf(infusionExecutionMap.get("batchNo"));
                        if(StringUtils.isNotBlank(inpatorderdataId) && StringUtils.isNotBlank(batchNo)){
                            if("0".equals(operationStatus)){
                                //0 封管
                                List<PuncureChannleEntity> list = this.puncureChannleMapper.selectPointListByOrderId(inpatorderdataId,Integer.parseInt(batchNo));
                                if (CollectionUtils.isNotEmpty(list)) {
                                    if (list.size() == 1) {
                                        PuncureChannleEntity puncureChannleEntity = list.get(0);
                                        puncureChannleEntity.setSpeedValue("");
                                        puncureChannleEntity.setSpeedElementId("");
                                        puncureChannleEntity.setChannleTypeValue("");
                                        puncureChannleEntity.setChannleTypeElementId("");
                                        puncureChannleEntity.setInstrumentValue("");
                                        puncureChannleEntity.setInstrumentElementId("");
                                        puncureChannleMapper.updateByPrimaryKeySelective(puncureChannleEntity);
                                    } else {
                                        List<PuncureChannleEntity> puncureChannleEntityList = puncureChannleMapper.selectOneByOrderAndBatch(inpatorderdataId,Integer.parseInt(batchNo));
                                        if (CollectionUtils.isNotEmpty(puncureChannleEntityList)) {
                                            puncureChannleMapper.deleteByPrimaryKey(puncureChannleEntityList.get(0));
                                        }
                                    }
                                }
                                //把当前任务的文书改成封管
                                //更改文书
                                this.ordersFileIndexDataMapper.updateEmrFileDataSealingTubeByInpatorderdataId(inpatorderdataId, batchNo);
                                //新增终止数据
                                this.insertAtomizeMedReturn(stopTaskDTO, userId);
                                //更新状态
                                taskExecuteMapper.updateTaskExecuteBatchById(userId, "1", taskBatchId, TaskEnum.TASKSTOP.getValue());
                                return ResultGenerator.genOkResult("终止成功");
                            }else if("1".equals(operationStatus)){
                                //1 拔针
                                //查询出所有相同穿刺点的任务，把所有任务对应的文书中的结束方式改成拔针，并结束任务
                                //输液中心关于此穿刺点下的输液任务流程的界面所有数据都清除
                                //任务执行的不要查出封管的时候通道
                                List<PuncureChannleEntity> list = this.puncureChannleMapper.selectPointListByOrderId2(inpatorderdataId, Integer.parseInt(batchNo), "1");
                                List<PuncureChannleEntity> puncureList = this.puncureChannleMapper.selectPointListByOrderId2(inpatorderdataId, Integer.parseInt(batchNo), null);
                                //任务处理
                                if (CollectionUtils.isNotEmpty(list)) {
                                    List<Map<String, Object>> batchList = new CopyOnWriteArrayList<>();
                                    list.stream().forEach(y -> {
                                       //批量更新文书
                                        Map<String, Object> entityMap = new HashMap<>();
                                        //判断是否当前节点是否暂停输液，如果是暂停输液，则把其他的文书内容也改成暂停输液
                                         //0 暂停  1 完成
                                        if(inpatorderdataId.equals(y.getInpatorderdataId()) && batchNo.equals(y.getBatchNo())){
                                            //更改文书
                                            this.ordersFileIndexDataMapper.updateEmrFileDataByInpatorderdataId(inpatorderdataId, batchNo);
                                            //新增终止数据
                                            this.insertAtomizeMedReturn(stopTaskDTO, userId);
                                            //更新状态
                                            taskExecuteMapper.updateTaskExecuteBatchById(userId, "1", taskBatchId, TaskEnum.TASKSTOP.getValue());

                                        }else{
                                            //0 暂停  1 完成
                                            if(StringUtils.isNotBlank(taskStatus) && "0".equals(taskStatus)){
                                                this.ordersFileIndexDataMapper.updateXSCZByInpatorderdataId(y.getInpatorderdataId(), y.getBatchNo());
                                                this.ordersFileIndexDataMapper.updateEmrFileDataByInpatorderdataId(y.getInpatorderdataId(), y.getBatchNo());
                                            }else if(StringUtils.isNotBlank(taskStatus) && "1".equals(taskStatus)){
                                                this.ordersFileIndexDataMapper.updateSYWCByInpatorderdataId(y.getInpatorderdataId(), y.getBatchNo());
                                                this.ordersFileIndexDataMapper.updateEmrFileDataByInpatorderdataId(y.getInpatorderdataId(), y.getBatchNo());
                                            }
                                            //2020-11-19输液暂停节点去除，之前的逻辑暂停会先到暂停节点下一步再输液中心，现在暂停直接进入输液中心，继续走下一个节点会找不到任务终止任务，需要过滤掉在输液中心的任务。
                                            TaskExecuteBatchEntity taskExecuteBatchEntity = taskExecuteBatchMapper.queryTaskBatchByInpatorderdataIdAndBatchNo(y.getInpatorderdataId(), y.getBatchNo());
                                            if (null != taskExecuteBatchEntity) {
                                                //获取要创建下个节点的BatchEntity
                                                taskExecuteBatchEntity.setExecutePersonId(userId);
                                                entityMap.put("taskExecuteDetailEntity", taskExecuteBatchEntity);
                                                entityMap.put("userId", userId);
                                                batchList.add(entityMap);
                                            }
                                        }


                                    });
                                    if (CollectionUtils.isNotEmpty(batchList)) {
                                        nursePatientOrderService.createNextTaskNodeList(batchList, null);
                                    }
                                }
                                //拔针后通道什么
                                if (CollectionUtils.isNotEmpty(puncureList)) {
                                    puncureList.stream().forEach(y -> {
                                        if (StringUtils.isNotBlank(y.getPunctureChannleId())) {
                                            String[] punctureChannleIds = y.getPunctureChannleId().split(",");
                                            for (String pId : punctureChannleIds) {
                                                puncureChannleMapper.deleteByPrimaryKey(pId);
                                            }
                                        }
                                    });
                                }
                                return ResultGenerator.genOkResult("终止成功");
                            }
                        }
                    }
                }
            }
        } else {
            //任务未生成
            this.insertAtomizeMedReturn(stopTaskDTO, userId);
            return ResultGenerator.genOkResult("终止成功");
        }
        return ResultGenerator.genFailedResult("此任务不能进行终止!");
    }

    /**
     * 注射终止
     *
     * @param stopTaskDTO
     * @param userId
     */
    public Result stopInjection(StopTaskDTO stopTaskDTO, String userId) {
        //判断是否有任务
        List<Map<String, Object>> taskList = taskExecuteMapper.queryTaskExecuteBatchByQrCode(stopTaskDTO.getQrCode(), null);
        if (CollectionUtils.isNotEmpty(taskList)) {
            //判断节点是否在输液中心，并且是执行过输液巡视  最后一个节点
            Map<String, Object> executeTaskMap = taskList.stream().filter(s -> "0".equals(s.get("status"))).findFirst().orElse(null);
            //倒数第二个节点
            if (executeTaskMap != null) {
                String varCode = (String) executeTaskMap.get("varCode");
                String taskBatchId = (String) executeTaskMap.get("taskBatchId");
                String taskName = (String) executeTaskMap.get("taskName");
                String emrFileId = (String) executeTaskMap.get("emrFileId");
                if (StringUtils.isNotBlank(varCode) &&
                        ((VarCodeEnum.RWJD_SYZX.getVarCode().equalsIgnoreCase(varCode) && TaskEnum.TASK_NAME_PNZS.getText().equals(taskName))
                                || VarCodeEnum.RWJD_BFBYHD.getVarCode().equalsIgnoreCase(varCode)
                                || VarCodeEnum.RWJD_BFJYHD.getVarCode().equalsIgnoreCase(varCode)
                                || VarCodeEnum.PXZS_JRZS.getVarCode().equalsIgnoreCase(varCode)
                                || VarCodeEnum.RWJD_SYZX.getVarCode().equalsIgnoreCase(varCode)
                                || VarCodeEnum.CZ_YDSZS.getVarCode().equalsIgnoreCase(varCode))) {
                    //新增终止数据
                    this.insertAtomizeMedReturn(stopTaskDTO, userId);
                    //更新状态
                    taskExecuteMapper.updateTaskExecuteBatchById(userId, "1", taskBatchId, TaskEnum.TASKSTOP.getValue());
                    return ResultGenerator.genOkResult("终止成功");
                } else if (StringUtils.isNotBlank(varCode) && VarCodeEnum.DSYJG.getVarCode().equalsIgnoreCase(varCode)) {
                    //碘实验前是加药摆药
                    //如果当前节点在输液中心，上一个节点为输液巡视
                    Map<String, Object> syxsMap = taskList.stream().skip(taskList.size() - 2).findFirst().orElse(null);
                    String syxsVarCode = (String) syxsMap.get("varCode");
                    if (StringUtils.isNotBlank(syxsVarCode) && VarCodeEnum.RWJD_BFJYHD.getVarCode().equalsIgnoreCase(syxsVarCode)) {
                        //新增终止数据
                        this.insertAtomizeMedReturn(stopTaskDTO, userId);
                        //更新状态
                        taskExecuteMapper.updateTaskExecuteBatchById(userId, "1", taskBatchId, TaskEnum.TASKSTOP.getValue());
                        return ResultGenerator.genOkResult("终止成功");
                    }
                }else if(StringUtils.isNotBlank(varCode) && VarCodeEnum.RWJD_SYXS.getVarCode().equalsIgnoreCase(varCode)){
                    //return ResultGenerator.genOkResult("终止成功");
                    //0 封管 1 拔针
                    String operationStatus = stopTaskDTO.getOperationStatus();
                    //0 暂停  1 完成
                    String taskStatus = stopTaskDTO.getTaskStatus();
                    Map<String, Object> infusionExecutionMap = taskList.stream().filter(x->"0".equals(x.get("status"))).findFirst().orElse(null);
                    if(infusionExecutionMap!=null) {
                        String inpatorderdataId = (String)infusionExecutionMap.get("inpatorderdataId");
                        String batchNo = String.valueOf(infusionExecutionMap.get("batchNo"));
                        if(StringUtils.isNotBlank(inpatorderdataId) && StringUtils.isNotBlank(batchNo)){
                            if("0".equals(operationStatus)){
                                //0 封管
                                List<PuncureChannleEntity> list = this.puncureChannleMapper.selectPointListByOrderId(inpatorderdataId,Integer.parseInt(batchNo));
                                if (CollectionUtils.isNotEmpty(list)) {
                                    if (list.size() == 1) {
                                        PuncureChannleEntity puncureChannleEntity = list.get(0);
                                        puncureChannleEntity.setSpeedValue("");
                                        puncureChannleEntity.setSpeedElementId("");
                                        puncureChannleEntity.setChannleTypeValue("");
                                        puncureChannleEntity.setChannleTypeElementId("");
                                        puncureChannleEntity.setInstrumentValue("");
                                        puncureChannleEntity.setInstrumentElementId("");
                                        puncureChannleMapper.updateByPrimaryKeySelective(puncureChannleEntity);
                                    } else {
                                        List<PuncureChannleEntity> puncureChannleEntityList = puncureChannleMapper.selectOneByOrderAndBatch(inpatorderdataId,Integer.parseInt(batchNo));
                                        if (CollectionUtils.isNotEmpty(puncureChannleEntityList)) {
                                            puncureChannleMapper.deleteByPrimaryKey(puncureChannleEntityList.get(0));
                                        }
                                    }
                                }
                                //把当前任务的文书改成封管
                                if(StringUtils.isNotBlank(emrFileId)) {
                                    //更改文书
                                    this.ordersFileIndexDataMapper.updateEmrFileDataSealingTubeByInpatorderdataId(inpatorderdataId, batchNo);
                                }
                                //新增终止数据
                                this.insertAtomizeMedReturn(stopTaskDTO, userId);
                                //更新状态
                                taskExecuteMapper.updateTaskExecuteBatchById(userId, "1", taskBatchId, TaskEnum.TASKSTOP.getValue());
                                return ResultGenerator.genOkResult("终止成功");
                            }else if("1".equals(operationStatus)){
                                //1 拔针
                                //查询出所有相同穿刺点的任务，把所有任务对应的文书中的结束方式改成拔针，并结束任务
                                //输液中心关于此穿刺点下的输液任务流程的界面所有数据都清除
                                //任务执行的不要查出封管的时候通道
                                List<PuncureChannleEntity> list = this.puncureChannleMapper.selectPointListByOrderId2(inpatorderdataId, Integer.parseInt(batchNo), "1");
                                List<PuncureChannleEntity> puncureList = this.puncureChannleMapper.selectPointListByOrderId2(inpatorderdataId, Integer.parseInt(batchNo), null);
                                //任务处理
                                if (CollectionUtils.isNotEmpty(list)) {
                                    if (list.size() != 1) {
                                        List<Map<String, Object>> batchList = new CopyOnWriteArrayList<>();
                                        list.stream().forEach(y -> {
                                            //批量更新文书
                                            Map<String, Object> entityMap = new HashMap<>();
                                            //判断是否当前节点是否暂停输液，如果是暂停输液，则把其他的文书内容也改成暂停输液
                                            //0 暂停  1 完成
                                            if(inpatorderdataId.equals(y.getInpatorderdataId()) && batchNo.equals(y.getBatchNo())){
                                                //新增终止数据
                                                this.insertAtomizeMedReturn(stopTaskDTO, userId);
                                                //更新状态
                                                taskExecuteMapper.updateTaskExecuteBatchById(userId, "1", taskBatchId, TaskEnum.TASKSTOP.getValue());
                                            }else{
                                                //0 暂停  1 完成
                                                if(StringUtils.isNotBlank(taskStatus) && "0".equals(taskStatus)){
                                                    this.ordersFileIndexDataMapper.updateXSCZByInpatorderdataId(y.getInpatorderdataId(), y.getBatchNo());
                                                    this.ordersFileIndexDataMapper.updateEmrFileDataByInpatorderdataId(y.getInpatorderdataId(), y.getBatchNo());
                                                }else if(StringUtils.isNotBlank(taskStatus) && "1".equals(taskStatus)){
                                                    this.ordersFileIndexDataMapper.updateSYWCByInpatorderdataId(y.getInpatorderdataId(), y.getBatchNo());
                                                    this.ordersFileIndexDataMapper.updateEmrFileDataByInpatorderdataId(y.getInpatorderdataId(), y.getBatchNo());
                                                }
                                                //2020-11-19输液暂停节点去除，之前的逻辑暂停会先到暂停节点下一步再输液中心，现在暂停直接进入输液中心，继续走下一个节点会找不到任务终止任务，需要过滤掉在输液中心的任务。
                                                TaskExecuteBatchEntity taskExecuteBatchEntity = taskExecuteBatchMapper.queryTaskBatchByInpatorderdataIdAndBatchNo(y.getInpatorderdataId(), y.getBatchNo());
                                                if (null != taskExecuteBatchEntity) {
                                                    //获取要创建下个节点的BatchEntity
                                                    taskExecuteBatchEntity.setExecutePersonId(userId);
                                                    entityMap.put("taskExecuteDetailEntity", taskExecuteBatchEntity);
                                                    entityMap.put("userId", userId);
                                                    batchList.add(entityMap);
                                                }
                                            }


                                        });
                                        if (CollectionUtils.isNotEmpty(batchList)) {
                                            nursePatientOrderService.createNextTaskNodeList(batchList, null);
                                        }
                                    }
                                }
                                //拔针后通道什么
                                if (CollectionUtils.isNotEmpty(puncureList)) {
                                    puncureList.stream().forEach(y -> {
                                        if (StringUtils.isNotBlank(y.getPunctureChannleId())) {
                                            String[] punctureChannleIds = y.getPunctureChannleId().split(",");
                                            for (String pId : punctureChannleIds) {
                                                puncureChannleMapper.deleteByPrimaryKey(pId);
                                            }
                                        }
                                    });
                                }
                                return ResultGenerator.genOkResult("终止成功");
                            }
                        }
                    }
                }
                /*else if (StringUtils.isNotBlank(varCode) && VarCodeEnum.RWJD_SYZX.getVarCode().equalsIgnoreCase(varCode)) {
                    //输液中心
                    //如果当前节点在输液中心，上一个节点为输液巡视
                    Map<String, Object> syxsMap = taskList.stream().skip(taskList.size() - 2).findFirst().orElse(null);
                    String syxsVarCode = (String) syxsMap.get("varCode");
                    if (StringUtils.isNotBlank(syxsVarCode) && VarCodeEnum.RWJD_SYXS.getVarCode().equalsIgnoreCase(syxsVarCode)) {
                        //新增终止数据
                        this.insertAtomizeMedReturn(stopTaskDTO, userId);
                        //更新状态
                        taskExecuteMapper.updateTaskExecuteBatchById(userId, "1", taskBatchId);
                        return ResultGenerator.genOkResult("终止成功");
                    }
                }*/
            }
        } else {
            //任务未生成
            this.insertAtomizeMedReturn(stopTaskDTO, userId);
            return ResultGenerator.genOkResult("终止成功");
        }
        return ResultGenerator.genFailedResult("此任务不能进行终止!");
    }

    /**
     * 注射终止
     *
     * @param stopTaskDTO
     * @param userId
     */
    public Result stopEnteralNutrition(StopTaskDTO stopTaskDTO, String userId) {
        //判断是否有任务
        List<Map<String, Object>> taskList = taskExecuteMapper.queryTaskExecuteBatchByQrCode(stopTaskDTO.getQrCode(), null);
        if (CollectionUtils.isNotEmpty(taskList)) {
            //判断节点是否在输液中心，并且是执行过输液巡视  最后一个节点
            Map<String, Object> executeTaskMap = taskList.stream().filter(s -> "0".equals(s.get("status"))).findFirst().orElse(null);
            //倒数第二个节点
            if (executeTaskMap != null) {
                String varCode = (String) executeTaskMap.get("varCode");
                String taskBatchId = (String) executeTaskMap.get("taskBatchId");
                if (StringUtils.isNotBlank(varCode) &&
                        (VarCodeEnum.RWJD_BFBYHD.getVarCode().equalsIgnoreCase(varCode)
                                || VarCodeEnum.RWJD_BFJYHD.getVarCode().equalsIgnoreCase(varCode)
                                || VarCodeEnum.CNYYGZ.getVarCode().equalsIgnoreCase(varCode))) {
                    //新增终止数据
                    this.insertAtomizeMedReturn(stopTaskDTO, userId);
                    //更新状态
                    taskExecuteMapper.updateTaskExecuteBatchById(userId, "1", taskBatchId, TaskEnum.TASKSTOP.getValue());
                    return ResultGenerator.genOkResult("终止成功");
                }
                /*else if (StringUtils.isNotBlank(varCode) && VarCodeEnum.CNYYGZ.getVarCode().equalsIgnoreCase(varCode)) {
                    //输液中心
                    //如果当前节点在输液中心，上一个节点为输液巡视
                    Map<String, Object> syxsMap = taskList.stream().skip(taskList.size() - 2).findFirst().orElse(null);
                    String syxsVarCode = (String) syxsMap.get("varCode");
                    if (StringUtils.isNotBlank(syxsVarCode) && VarCodeEnum.CNYYXS.getVarCode().equalsIgnoreCase(syxsVarCode)) {
                        //新增终止数据
                        this.insertAtomizeMedReturn(stopTaskDTO, userId);
                        //更新状态
                        taskExecuteMapper.updateTaskExecuteBatchById(userId, "1", taskBatchId);
                        return ResultGenerator.genOkResult("终止成功");
                    }
                }*/
            }
        } else {
            //任务未生成
            this.insertAtomizeMedReturn(stopTaskDTO, userId);
            return ResultGenerator.genOkResult("终止成功");
        }
        return ResultGenerator.genFailedResult("此任务不能进行终止!");

    }

    public Result deletePuncturePoint(String inpatNum, String pointValue){
        List<PuncureChannleEntity> puncureChannleEntities = taskExecuteMapper.puncureChannleList(inpatNum, pointValue);
        if(CollectionUtils.isNotEmpty(puncureChannleEntities)){
            return ResultGenerator.genFailedResult("该穿刺点下有任务不能删除!");
        }else{
            taskExecuteMapper.deletePuncureChannle(inpatNum, pointValue);
            return ResultGenerator.genOkResult(pointValue+"穿刺点删除成功!");
        }
    }


    public void insertAtomizeMedReturn(StopTaskDTO stopTaskDTO, String userId) {
        Map<String, String> patientInfo = patientMapper.queryPatientInfo(stopTaskDTO.getInpatNum());
        AtomizeMedReturnEntity atomizeMedReturnEntity = new AtomizeMedReturnEntity();
        atomizeMedReturnEntity.setQrCode(stopTaskDTO.getQrCode());
        atomizeMedReturnEntity.setInpatNum(stopTaskDTO.getInpatNum());
        atomizeMedReturnEntity.setInpatorderdataId(stopTaskDTO.getInpatorderdataId());
        if (VarCodeEnum.QT.getName().equals(stopTaskDTO.getReturnReason())) {
            atomizeMedReturnEntity.setReturnReason(stopTaskDTO.getOtherReason());
        } else {
            atomizeMedReturnEntity.setReturnReason(stopTaskDTO.getReturnReason());
        }
        atomizeMedReturnEntity.initAdd();
        atomizeMedReturnEntity.setReturnId(UUIDUtil.randomString());
        atomizeMedReturnEntity.setDeptId(patientInfo.get("deptId"));
        atomizeMedReturnEntity.setWardDeptId(patientInfo.get("wardDeptId"));
        atomizeMedReturnEntity.setReturnTime(new Timestamp(System.currentTimeMillis()));
        atomizeMedReturnEntity.setReturnUserId(userId);
        atomizeMedReturnEntity.setDelFlag(ConstsEnum.DEFAULT_NO.getIndex());
        atomizeMedReturnEntity.setType(ConstsEnum.ATOMIZE_MED_RETURN_TWO.getIndex());
        atomizeMedReturnMapper.insert(atomizeMedReturnEntity);
    }


    public Result queryTaskStatusByQrCode(StopTaskDTO stopTaskDTO){
        //flag  0 不出提示  1 出提示
        String flag="0";
        if ("0".equals(stopTaskDTO.getStatus()) || "1".equals(stopTaskDTO.getStatus())) {
            if ("输液".equals(stopTaskDTO.getFunMark())) {
                List<Map<String, Object>> infusionExecutionList = taskExecuteMapper.queryTaskExecuteBatchByQrCode(stopTaskDTO.getQrCode(), "0");
                if(CollectionUtils.isNotEmpty(infusionExecutionList)){
                    Map<String, Object> infusionExecutionMap = infusionExecutionList.get(0);
                    //输液巡视
                    if(StringUtils.isNotBlank((String)infusionExecutionMap.get("varCode")) && VarCodeEnum.RWJD_SYXS.getVarCode().equals((String)infusionExecutionMap.get("varCode"))){
                        flag="1";
                    }
                }
            }else if ("注射".equals(stopTaskDTO.getFunMark())) {
                List<Map<String, Object>> infusionExecutionList = taskExecuteMapper.queryTaskExecuteBatchByQrCode(stopTaskDTO.getQrCode(), "0");
                if(CollectionUtils.isNotEmpty(infusionExecutionList)){
                    Map<String, Object> infusionExecutionMap = infusionExecutionList.get(0);
                    //输液巡视
                    if(StringUtils.isNotBlank((String)infusionExecutionMap.get("taskName")) && TaskEnum.TASK_NAME_JMZS.getValue().equals((String)infusionExecutionMap.get("taskName")) &&
                            StringUtils.isNotBlank((String)infusionExecutionMap.get("varCode")) && VarCodeEnum.RWJD_SYXS.getVarCode().equals((String)infusionExecutionMap.get("varCode"))){
                        flag="1";
                    }
                }
            }
        }
        stopTaskDTO.setInspectionFlag(flag);
        return ResultGenerator.genOkResult(stopTaskDTO);
    }

    public Result queryTaskPuncturePointByQrCode(StopTaskDTO stopTaskDTO){
        String flag="0";
        if (("0".equals(stopTaskDTO.getStatus()) || "1".equals(stopTaskDTO.getStatus()) && ("输液".equals(stopTaskDTO.getFunMark()) || "注射".equals(stopTaskDTO.getFunMark())))) {
            //0 封管 1 拔针
            String operationStatus = stopTaskDTO.getOperationStatus();
            if("1".equals(operationStatus)){
                List<Map<String, Object>> infusionExecutionList = taskExecuteMapper.queryTaskExecuteBatchByQrCode(stopTaskDTO.getQrCode(), "0");
                if(CollectionUtils.isNotEmpty(infusionExecutionList)) {
                    Map<String, Object> infusionExecutionMap = infusionExecutionList.get(0);
                    String inpatorderdataId = (String)infusionExecutionMap.get("inpatorderdataId");
                    String batchNo = String.valueOf(infusionExecutionMap.get("batchNo"));
                    if(StringUtils.isNotBlank(inpatorderdataId) && StringUtils.isNotBlank(batchNo)){
                        List<PuncureChannleEntity> list = this.puncureChannleMapper.selectPointListByOrderId(inpatorderdataId,Integer.parseInt(batchNo));
                        if(CollectionUtils.isNotEmpty(list) && list.size()==1){
                            if(inpatorderdataId.equals(list.get(0).getInpatorderdataId()) && batchNo.equals(list.get(0).getBatchNo())){
                                flag="1";
                            }
                        }
                    }
                }
            }
        }
        stopTaskDTO.setSelectTaskFlag(flag);
        return ResultGenerator.genOkResult(stopTaskDTO);
    }
}
